Reputation: 669
I am trying to serialize an array and want to attach an attribute to the array. For example, the output I want is:
<ArrayOfThingie version="1.0">
<Thingie>
<name>one</name>
</Thingie>
<Thingie>
<name>two</name>
</Thingie>
</ArrayOfThingie>
This is just a primitive array, so I don't want to define the attribute for the array itself, just in its serialization. Is there a way to inject an attribute into the serialization?
Upvotes: 2
Views: 863
Reputation: 48265
You could create a wrapper for ArrayOfThingie
just for serialization:
public class Thingie
{
[XmlElement("name")]
public string Name { get; set; }
}
[XmlRoot]
public class ArrayOfThingie
{
[XmlAttribute("version")]
public string Version { get; set; }
[XmlElement("Thingie")]
public Thingie[] Thingies { get; set; }
}
static void Main(string[] args)
{
Thingie[] thingies = new[] { new Thingie { Name = "one" }, new Thingie { Name = "two" } };
ArrayOfThingie at = new ArrayOfThingie { Thingies = thingies, Version = "1.0" };
XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfThingie));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, at);
Console.WriteLine(writer.ToString());
}
Upvotes: 2
Reputation: 26494
A bit of a hack would be to serialize the array to XML and then modify the serialized XML before saving. A cleaner way assuming the Array is a property of a class would be to Add an attribute to a serialized XML node.
Upvotes: 0