1

I have looked at several other questions for this same issue but have not been able to resolve my problem. I have classes, code, and XML as follows. However, after the Deserialize call my type variable contains a TestList array which contains a TestElement but the TestElement is null. Appreciate any help. Thanks.

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace TestXMLSerialization
{
    class Program
    {
        static void Main(string[] args) {
            XmlSerializer ser = new XmlSerializer(typeof(TestRootElement));
            string xmlString = "<?xml version=\"1.0\" ?><TestRootElement><TestList><TestItem><TestElement>Test Data</TestElement></TestItem></TestList></TestRootElement>";
            TestRootElement type = (TestRootElement)ser.Deserialize(new StringReader(xmlString));

            Console.WriteLine(type.TestList[0].TestElement);
        }
    }

    [Serializable()]
    [System.Xml.Serialization.XmlRoot("TestRootElement")]
    public class TestRootElement
    {
        [System.Xml.Serialization.XmlElement("TestList")]
        public List<TestItem> TestList { get; set; }
    }

    [Serializable()]
    [System.Xml.Serialization.XmlType("TestItem")]
    public class TestItem
    {
        [System.Xml.Serialization.XmlElement("TestElement")]
        public string TestElement { get; set; }
    }
}
2
  • 4
    You have too many XmlRoot attributes - a document has one root, in this case TestRootElement. Commented Oct 25, 2012 at 20:35
  • Thanks @Oded. However, that does not seem to be the issue. I have corrected the code to use XmlType but still get a null value for TestElement. Commented Oct 26, 2012 at 12:18

1 Answer 1

2

Turns out the code works fine without any Serialization attributes.

public class TestRootElement
{
    public List<TestItem> TestList { get; set; }
}

public class TestItem
{
    public string TestElement { get; set; }
}

So adding the attributes back in one at a time I found that the List<> needed an XmlArray attribute instead of XmlElement.

[Serializable()]
[System.Xml.Serialization.XmlRoot("TestRootElement")]
public class TestRootElement
{
    [XmlArray("TestList")]
    public List<TestItem> TestList { get; set; }
}

[Serializable()]
[XmlType("TestItem")]
public class TestItem
{
    [XmlElement("TestElement")]
    public string TestElement { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.