Mathijs Segers
Mathijs Segers

Reputation: 6238

DeSerialize xml string and ignore the first element within root

I've got this XML data in string, structure can be seen as follows:

  <Document>
     <Contents>
        <Content>
        ...
     <Contents>
  </Document>

So the structure is always like above, I made a class which exactly reflects the objects which will be identified as <Content>.

I wonder how I can deserialize the content in one go into a List of Content objects. Currently I try something as

XmlSerializer annotationSerializer = new XmlSerializer(
            typeof(List<Content>),
            new XmlRootAttribute("Document")
        );

Of course this will not work as the first found element will be contents, how do I work around this? Do I require a certain attribute on the Content class?

Upvotes: 1

Views: 802

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064114

You will need to use a root object here:

public class Document {
   public List<Content> Contents {get;} = new List<Content>();
}

Now deserialize a Document and read .Contents. There are some scenarios where you can bypass the root object, but... not here, not conveniently.

Upvotes: 1

Related Questions