aggsol
aggsol

Reputation: 2480

Named XML serialization of List

I derived from List<int> and want to XML serilaize with custom names. Example:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
namespace xmlerror
{
    [Serializable, XmlRoot("Foo")]
    public class Foo : List<int>
    {
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            var foo = new Foo();
            foo.Add(123);

            using (var writer = new StringWriter())
            {
                var serilizer = new XmlSerializer(typeof(Foo));
                serilizer.Serialize(writer, foo);
                Console.WriteLine(writer.ToString());
            }             
        }
    }
}

Output:

<?xml version="1.0" encoding="utf-16"?>
<Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <int>123</int>
</Foo>

But I want to name the element <Bar> instead of <int>. I tried the XML attributes XmlAnyElement and XmlArrayItem but to no end. How can I change the name of the element tags? Do I have to do it manually with XmlTextWriter?

Upvotes: 0

Views: 41

Answers (2)

Alexander Petrov
Alexander Petrov

Reputation: 14231

There are many ways to do it.

For example you can implement IXmlSerializable interface.

[XmlRoot("Foo")]
public class Foo : List<int>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(XmlReader reader)
    {
        reader.ReadToFollowing("Bar");

        while (reader.Name == "Bar")
            this.Add(reader.ReadElementContentAsInt());
    }

    public void WriteXml(XmlWriter writer)
    {
        foreach (var n in this)
            writer.WriteElementString("Bar", n.ToString());
    }
}

Upvotes: 1

Charles Mager
Charles Mager

Reputation: 26213

The most obvious solution to use something other than int.

public class Bar 
{
    public Bar(int value)
    {
        Value = value;
    }

    public Bar()
    {

    }

    [XmlText]
    public int Value { get; set; }
}

public class Foo : List<Bar>
{

}

See this fiddle for a working demo.

As an aside, the Serializable attribute is not related to XmlSerializer and can be omitted.

Upvotes: 1

Related Questions