Search code examples
c#serializationxml-serializationxmlroot

Serializing class decorated with XmlRoot, error when used in List


When i try to serialize a class element of type Test, it gives an xml with root element as "testing" which is set using XmlRoot.

But when I try to serialize an element of class Elems, Test element is serialized with root element "Test" instead of "testing".

[XmlRoot("testing")]
public class Test
{
}

public class Elems
{
   public List<Test> how = new List<Test>();

    public Elems()
    {
        how.Add(new Test());
        how.Add(new Test());
        how.Add(new Test());
    }
}

This the Output when Elems is serialized,

<Elems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x
mlns:xsd="http://www.w3.org/2001/XMLSchema">
  <how>
    <Test />
    <Test />
    <Test />
  </how>
</Elems>

instead this is what i need.

<Elems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x
mlns:xsd="http://www.w3.org/2001/XMLSchema">
  <how>
    <testing />
    <testing />
    <testing />
  </how>
</Elems>

Thanks


Solution

  • Try like this:

    public class Test { }
    
    public class Elems
    {
        public Elems()
        {
            How = new List<Test>();
            How.Add(new Test());
            How.Add(new Test());
            How.Add(new Test());
        }
    
        [XmlArray("how")]
        [XmlArrayItem("testing")]
        public List<Test> How { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var elems = new Elems();
            var serializer = new XmlSerializer(elems.GetType());
            serializer.Serialize(Console.Out, elems);
        }
    }