Search code examples
c#xmldeserializationxml-deserialization

XML-Deserialization of a nested List C#


I am trying to deserialize a Xml File using the XmlSerializer. A part of my file looks like this:

<bla>
    <ListOfListOfTest>
         <ListOfTest> 
               <Test>       
               </Test>        
        </ListOfTest>        
    </ListOfListOfTest>
</bla>

I tried different ways but it does not work.

My first try looked like:

public class bla
    {
        public bla()
        {
            ListOfListOfTest = new List<List<Test>>();
        }
        [...]
        public List<List<Test>> ListOfListOfTest{ get; set; }            
    }

-> does not work.

Second try:

public class bla
    {
        public bla()
        {
            ListOfListOfTest = new List<List<Test>>();
        }
        [..]
        public List<List<Test>> ListOfListOfTest { get; set; }

        [XmlArrayItemAttribute]
        public List<List<Test>> listOfListOfTest { get { return ListOfListOfTest ; } }
    }

-> failed as well

Third try:

public class bla
    {
        public bla()
        {
            ListOfListOfTest = new List<Foo>();
        }
        [...]
        public List<Foo> ListOfListOfTest { get; set; }

    }


    public class Foo
    {
        public Foo()
        {
            ListOfTest = new List<Test>();   
        }
        public List<Test> ListOfTest { get; set; }
    }

-> failed...

Failed means that the XmlSerializer does not fill the List during serializer.Deserialize(). I´m always getting a List with zero Elements in it.

What am i doing wrong?

thanks for your effort


Solution

  • Something like this?

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Xml.Serialization;
    
    class Program {
        static void Main() {
            var xml = @"<bla>
        <ListOfListOfTest>
             <ListOfTest> 
                   <Test>       
                   </Test>        
            </ListOfTest>        
        </ListOfListOfTest>
    </bla>";
            var bar = (Bar)new XmlSerializer(typeof(Bar)).Deserialize(new StringReader(xml));
            Console.WriteLine(bar.Lists.Sum(_ => _.Items.Count)); // 1
        }
    }
    [XmlRoot("bla")]
    public class Bar {
        [XmlArray("ListOfListOfTest")]
        [XmlArrayItem("ListOfTest")]
        public List<Foo> Lists { get; } = new List<Foo>();
    }
    public class Foo {
        [XmlElement("Test")]
        public List<Test> Items { get; } = new List<Test>();
    }
    public class Test { }
    

    The actual layout depends on which elements might be duplicated, and whether you need to be able to reproduce the exact organisation (vs just wanting all the Test items). In the code above, ListOfListOfTest is not expected to be duplicated, but there can be any number of ListOfTest or Test elements.