Search code examples
c#xmldeserializationxmlroot

XmlRoot attribute is needed to deserialize but in xml file there is no root attribute


I have a question: I have an .xml file

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items>
    <item>
      <id>2</id>
      <title>Live Test Event</title>
      <tournament>
        <id>6</id>
        <name>Test tournament</name>
        <property>
          <id>4</id>
          <name>Test property</name>
          <sport>
            <id>3</id>
            <name>Test Sport</name>
          </sport>
        </property>
      </tournament>
      <updatedAt>2018-01-22T11:11:44+0000</updatedAt>
      <startDate>2017-01-01T00:00:00+0000</startDate>
      <endDate>2018-12-31T00:00:00+0000</endDate>
    </item>
    ...
</items>

Also I have a class:

public class StreamingEvents
{
    [XmlArray("items")]
    [XmlArrayItem("item")]
    public List<Event> Events { get; set; }
}

And to deserialize this file I need to put an XmlRoot attribute before class declaration. But the problem is that I don't have the root attribute in my .xml. I have only an array "items". And I need to use XmlRoot attr to deserialize without errors. Could anybody help me?


Solution

  • I believe <items> is the root of the xml. In that case, your class should be as below in order to deseralize your xml successfully

    [XmlRoot("items")]
    public class StreamingEvents
    {
        [XmlElement("item")]
        public List<Event> Events { get; set; }
    }