C# XML parsing with LINQ storing directly to a struct?
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,
开发者_如何学Python 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 Book
and Chapter
are the following
class Book
{
public string Version { get; set; }
public string Type { get; set; }
public List<Chapter> Chapters { get; set; }
}
class Chapter
{
public int Number { get; set; }
public string Title { get; set; }
}
Then to use the XML to create a Book
object, we can do this
Book book = new Book
{
Version = xmlDoc.Root.Element("version").Value,
Type = xmlDoc.Root.Element("type").Value,
Chapters = (from chapter in xmlDoc.Descendants("chapters")
select new Chapter
{
Number = (int)chapter.Element("chapter"),
Title = chapter.Element("title").Value
}).ToList()
};
Note: 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.
精彩评论