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?

2 Answers 2

2

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());
    }
Sign up to request clarification or add additional context in comments.

1 Comment

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!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.