Search code examples
c#xmlserializationattributes

How to add a namespace prefix to XML attribute


I have a class that represents XML element:

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.testingmcafeesites.com/testcat_bl.html")]
[System.Xml.Serialization.XmlRootAttribute("scenario", Namespace = "http://www.testingmcafeesites.com/testcat_bl.html", IsNullable = false)]
public partial class scenario
{
    private string nameField;
    
    private description descriptionField;
    
    /// <remarks />
    [System.Xml.Serialization.XmlAttributeAttribute("name", Namespace = "http://www.testingmcafeesites.com/testcat_bl.html")]
    public string Name
    {
        get { return this.nameField; }
        set { this.nameField = value; }
    }
    
    /// <remarks />
    [System.Xml.Serialization.XmlElementAttribute("description", Namespace = "http://www.testingmcafeesites.com/testcat_bl.html")]
    public description description
    {
        get { return this.descriptionField; }
        set { this.descriptionField = value; }
    }
    
    /// <remarks />
    [System.Xml.Serialization.XmlNamespaceDeclarations]
    public System.Xml.Serialization.XmlSerializerNamespaces XmlNamespaces
    {
        get
        {
            var namespaces = new System.Xml.Serialization.XmlSerializerNamespaces();
            namespaces.Add("epd", "http://www.testingmcafeesites.com/testcat_bl.html");
            return namespaces;
        }
        set { }
    }
}

After serialization, it gives the following result:

<epd:scenario name="Reuse">

, but I need to get:

<epd:scenario epd:name="Reuse">

Could someone help me to explain what I should do to achieve the needed result?

I've tried to add epd:name prefix directly into XmlAttributeAttribute, but here the serialization breaks down

[System.Xml.Serialization.XmlAttributeAttribute("epd:name", Namespace = "http://www.testingmcafeesites.com/testcat_bl.html")]
public string Name
{
    get { return this.nameField; }
    set { this.nameField = value; }
}

Solution

  • Add Form = XmlSchemaForm.Qualified in the XmlAttribute.

    [System.Xml.Serialization.XmlAttributeAttribute("name", 
        Namespace = "http://www.testingmcafeesites.com/testcat_bl.html", 
        Form = XmlSchemaForm.Qualified)]
    public string Name
    {
        get { return this.nameField; }
        set { this.nameField = value; }
    }
    

    Reference: XmlAttributeAttribute.Form Property