Search code examples
c#datacontract

Cannot get element list using DataContractSerializer


I am unable to retrieve a collection of "test" elements from my XML. I can't figure out what is wrong with my syntax.

Here is the XML below:

<tests>
  <username>Me</username>
  <password>meme</password>
  <test>
    <title>Test This</title>
    <description>To verify this</description>
  </test>
  <test>
    <title>Test That</title>
    <description>To verify that</description>
  </test>
</tests>

And here is the C# class:

namespace MyProject
{
    public class Temp
    {
        [DataContract(Name = "tests", Namespace = "")]
        public class Tests
        {
            [DataMember(Name = "username", Order = 0)]
            public string Username { get; set; }

            [DataMember(Name = "password", Order = 1)]
            public string Password { get; set; }

            [DataMember(Name = "test", Order = 2)]
            public List<Test> testList;

            public Tests()
            {
            }

        }

        [DataContractCollection(Name = "test", Namespace = "")]
        public class Test : List<Test>
        {
            [DataMember(Name = "title", Order = 0)]
            public string Title { get; set; }

            [DataMember(Name = "description", Order = 1)]
            public string Description{ get; set; }

            public Test()
            { }

            public Test(String title, String desc)
            {
                this.Title = title;
                this.Description= desc;
            }


        }

    }
}

And my code to serialize:

FileStream fs = new FileStream("C:/bla/file.xml", FileMode.Open);
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer serializer = new DataContractSerializer(typeof(Temp3.TestGroup), knownTypeList);
Tests tests = (Tests)serializer.ReadObject(reader, true);
reader.Close();
fs.Close();

In debug mode, tests.testList has nothing. If I were to change public List<Test> testList; to public Test testList; I would get the first test element. I've tried using Test[] or ArrayList too.

Can one point out what is wrong? Thanks very much.

As a side question, is there a detailed sample of DataContractSerialization of XML (with deep nested elements) out there? Most of what I found was pretty basic.


Solution

  • Well I think i figured it out - at least partly. Thanks to this: http://borismod.blogspot.com/2009/06/v2-wcf-collectiondatacontract-and.html

    Other thing I found is I had to remove Order from [DataMember(Name = "test", Order = 2)] public List testList

    With the sample from the blog, my test elements would be enclosed by testlist. So testlist is an extra element.