Search code examples
c#arraysxmlserialization

C# Deserialize an XML array containing another array


I've got an xml I'd like to deserialize to classes

<MAINELEMENT>
  <ARRAY1>
    <ARRAY2 Array2Attr="Array2Attr">
      <ARRAY2ITEM Array2ItemAttr="Array2ItemAttr">Value</ARRAY2ITEM>
      <ARRAY2ITEM Array2ItemAttr="Array2ItemAttr">Value</ARRAY2ITEM>
      <ARRAY2ITEM Array2ItemAttr="Array2ItemAttr">Value</ARRAY2ITEM>
      <ARRAY2ITEM Array2ItemAttr="Array2ItemAttr">Value</ARRAY2ITEM>
    </ARRAY2>
    <ARRAY2 Array2Attr="Array2Attr">
      <ARRAY2ITEM Array2ItemAttr="Array2ItemAttr">Value</ARRAY2ITEM>
    </ARRAY2>
  </ARRAY1>
</MAINELEMENT>

Here is my code, and the problem is that Array2Items becomes null. Obviously, class Array2 should be an array instead of containing one. How can I do that?

    [XmlRoot("MAINELEMENT")]
    public class MainElement
    {
        [XmlArray("ARRAY1")]
        [XmlArrayItem("ARRAY2", Type = typeof(Array2))]
        public Array2[] Array2s { get; set; }

        public MainElement()
        {
        }
    }

    public class Array2
    {
        [XmlAttribute("Array2Attr")] public string Array2Attr { get; set; }
        [XmlArrayItem("ARRAY2ITEM", Type = typeof(Array2Item))]
        public Array2Item[] Array2Items { get; set; }

        public Array2()
        {
        }
    }

    public class Array2Item
    {
        [XmlAttribute("Array2ItemAttr")] public string Array2ItemAttr { get; set; }
        [XmlText] public string Value { get; set; }

        public Array2Item()
        {
        }
    }


Solution

  • Try :

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XmlReader reader = XmlReader.Create(FILENAME);
                XmlSerializer serializer = new XmlSerializer(typeof(MainElement));
                MainElement mainElement = (MainElement)serializer.Deserialize(reader);
            }
        }
        [XmlRoot("MAINELEMENT")]
        public class MainElement
        {
            [XmlArray("ARRAY1")]
            [XmlArrayItem("ARRAY2")]
            public Array2[] Array2s { get; set; }
    
        }
    
        public class Array2
        {
            [XmlElement("ARRAY2ITEM")]
            public Array2Item[] Array2Items { get; set; }
        }
        public class Array2Item
        {
            [XmlAttribute]
            public string Array2ItemAttr { get; set; }
            [XmlText]
            public string value { get; set; }
        }
    }