Show all posts.
I was wondering how to easily parse a simple xml structure and build an object list from it, and here it is a solution with LINQ to XML:
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
XDocument xd = XDocument.Parse(@"
<xml>
<book Author=""Moszi"" Title=""First book"" />
<book Author=""Eszto"" Title=""Second book"" />
<book Author=""Eszto"" Title=""Second book - 2nd edition"" />
</xml>");
var q = from c in xd.Descendants()
where c.Name == "book" && c.Attribute("Author").Value == "Eszto"
select new { Author = c.Attribute("Author").Value,
Title = c.Attribute("Title").Value
};
foreach (var qValue in q)
{
Console.WriteLine(qValue);
}
|
What we can notice here is the usage of c.Attribute("Title") - while the XElement.Attribute() take an XName as a parameter and the correct form would be c.Attribute(XName.Get("Title")) the framework designers have come up with an operator to make our life easier :) ...
|