views:

210

answers:

2

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?

A: 

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.

ahsteele
+1  A: 

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());
    }
bruno conde
Nice. I had been approaching as a job for the XmlSerializer namespace. That has a bunch of methods that do almost what I want, but not quite. This is much simpler. Thanks!
Jerry