C# XML parsing with LINQ storing directly to a struct?
- by Luke
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));
}