C# XML parsing with LINQ storing directly to a struct?

Posted by Luke on Stack Overflow See other posts from Stack Overflow or by Luke
Published on 2011-01-17T18:19:55Z Indexed on 2011/01/17 18:53 UTC
Read the original article Hit count: 157

Filed under:
|
|
|

Say I have the following XML schema:

<root>
   <version>2.0</version>
   <type>fiction</type>
   <chapters>
      <chapter>1</chapter>
      <title>blah blah</title>
   </chapter>
   <chapters>
      <chapter>2</chapter>
      <title>blah blah</title>
   </chapters>
</root>

Would it be possibly to parse the elements which I know will not be repeated in the XML and store them directly into the struct using LINQ?

For example, could I do something like this for "version" and "type"

//setup structs
Book book = new Book();
book.chapter = new Chapter();

//use LINQ to parse the xml
var bookData = from b in xmlDoc.Decendants("root")
               select new
               {
                   book.version = b.Element("version").Value,
                   book.type = b.Element("type").Value
               };

//then for "chapters" since I know there are multiple I can do:
var chapterData = from c in xmlDoc.Decendants("root"
                  select new
                  {
                    chapter = c.Element("chapters")   
                  };

foreach (var ch in chapterData)
{
    book.chapter.Add(getChapterData(ch.chapter));
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml