How do I add a attribute to a XmlArray element (XML Serialization)?

123Developer picture 123Developer · Jun 27, 2009 · Viewed 29.9k times · Source

How do I add a attribute to a XmlArray element ( not to XmlArrayItem ) while serializing the object?

Answer

Ray Lu picture Ray Lu · Jun 27, 2009

XmlArray is used to tell the xmlserializer to treat the property as array and serialize it according its parameters for the element names.

[XmlArray("FullNames")]
[XmlArrayItem("Name")]
public string[] Names{get;set;}

will give you

<FullNames>
    <Name>Michael Jackson</Name>
    <Name>Paris Hilton</Name>
</FullNames>

In order to add an xml attribute to FullNames element, you need declare a class for it.

[XmlType("FullNames")]
public class Names
{
   [XmlAttribute("total")]
   public int Total {get;set;} 
   [XmlElement("Name")]
   public string[] Names{get;set;}
}

This will give you

<FullNames total="2">
    <Name>Michael Jackson</Name>
    <Name>Paris Hilton</Name>
</FullNames>