Search code examples
c#xmlxmlserializer

Can a field have XmlAttribute and XmlElement attributes?


I need to read/write a xml element in any of the following ways.

<element param="..." set="...">
</element>

<element>
 <param>...</param>
 <set>...</set>
</element>

<element param="...">
 <set>...</set>
</element>

<element set="...">
 <param>...</param>
</element>

Is it possible to have a class with this form to do the work?

[XmlType("element")]
public class Element
{
  [XmlAttribute, XmlElement]
  public string param { get; set; }
  [XmlAttribute, XmlElement]
  public string set { get; set; }
}

Solution

  • Are you looking for a XML class which can have Element and Attribute with the same name like this one?

        [XmlRootAttribute(ElementName = "element")]
        public class ElementRoot
        {
            [XmlAttribute("param")]
            public string paramAtribute;
    
            [XmlElement("param")]
            public string paramElement;
    
            [XmlAttribute("set")]
            public string setAtribute;
    
            [XmlElement("set")]
            public string setElement;
        }
    

    XML:

    <?xml version="1.0" encoding="UTF-8"?>
    <element xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" param="..." set="...">
       <param>...</param>
       <set>...</set>
    </element>