Danny Ellis Jr.
Danny Ellis Jr.

Reputation: 1706

C# Deserialize Array as root element

I have an XML document I need to deserialize where the root element is an array of items, such as

<Items>
  <Item></Item>
  <Item></Item>
</Items>

I have tried creating a class that inherits from a collection such as like...

public class Items : IEnumerable<Item>

but I have not been able to get it to work. I get an error that says, <items> is not expected. I am not even sure it is possible to do what I'm trying to do.

Upvotes: 0

Views: 472

Answers (1)

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

The following declaration of the Items class works as you need:

[XmlRoot("Items")]
public class Items : List<Item>
{
}

The XmlRootAttribute does the trick, letting the XmlSerializer know about the root element. It then expects elements for items named according to the the Item class.

Upvotes: 2

Related Questions