C# XmlSerializer, Add an attribute to an array element
By admin - Last updated: Friday, June 27, 2008 - Save & Share - One Comment
In order words, add an attribute to an object element after xml serialization,
If you want something like,
<Rats count=“2”>
<Rat>little rat</Rat>
<Rat>old rat</Rat>
</Rats>
<Rat>little rat</Rat>
<Rat>old rat</Rat>
</Rats>
The C# code is
[XmlType(“Rats”)]
public class Rats
{
[XmlAttribute(“count”)]
public int Count { get; set; }
[XmlElement(“Rat”)] // now the array element will be as same as the object element Rats.
public string[] Rat { get; set; }
}
public class Rats
{
[XmlAttribute(“count”)]
public int Count { get; set; }
[XmlElement(“Rat”)] // now the array element will be as same as the object element Rats.
public string[] Rat { get; set; }
}
Traditional xml array serialization would get the extra element for the array itself.
[XmlType(“Rats”)]
public class Rats
{
[XmlAttribute(“count”)]
public int Count { get; set; }
[XmlArray(“Rats”)]
[XmlArrayItem(“Rat”)]
public string[] Rat { get; set; }
}
public class Rats
{
[XmlAttribute(“count”)]
public int Count { get; set; }
[XmlArray(“Rats”)]
[XmlArrayItem(“Rat”)]
public string[] Rat { get; set; }
}
<Rats count=“2”>
<Rats>
<Rat>little rat</Rat>
<Rat>old rat</Rat>
</Rats>
</Rats>
<Rats>
<Rat>little rat</Rat>
<Rat>old rat</Rat>
</Rats>
</Rats>
ta
Comment from Jon Kragh
Time August 25, 2010 at 6:48 am
Thanks much! Very useful tip.