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));
}
Given your XML example, you should be able to parse the XML in a single spot. For the sake of this answer, let’s assume your
BookandChapterare the followingThen to use the XML to create a
Bookobject, we can do thisNote: I’m going with classes here because structs should be small and (preferrably) immutable, whereas your book and its chapters can be the latter but not likely to be the former. The fact that the object is encapsulating other non-structs is a dead giveaway to me that the object should also not be struct.