views:

1136

answers:

2

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

Thanks and regards

123Developer

+4  A: 

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>
codemeit
yeah, I know this.. May be I didn't explain properly..let me explain with your example<ArrayOfString total="2"> <string>Michael Jackson</string> <string >Paris Hilton</string></ArrayOfString>See the "total" attribute for ArrayOfString element.. How do I get this?
123Developer
you'd have [XmlAttribute("total")] public int Total {get {return Names.Length;} set {}} or similar; note the "do nothing" setter.
Marc Gravell
(...using the same approach as codemeit has already shown to declare it)
Marc Gravell
A: 

Adding an attribute to an XmlArray

rahul