- bits & pieces about software development HostingAbc Logo
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 :) ...
add linkThe last comments:lucifer says:oh, i see now :D lucifer says:"If the LINQ runtime just thrown an exception similar to this one to your face". which one? :)apco says:1) Define the original issue. 2) The sorted list is sorted on value and there is not a key! 3) dark green text with black background: not too easy to read.moszidev says:Actually I've made these 2 forms with Expression Blend. I'm not sure if the extensive designing capabilities will be included in the VS designer ...Venemo says:I've just tried out Visual Studio 2008 Express, and it doesn't have the functionality to rotate the controls, but when I copied your source code, it recognised it. Anyway, it seems very similar to VS 2005, and only has a few improvements in its interBéla says:At long last! I'm looking forward to it! Keep it up! and so on ;)
Copyright (C) 2007, Molnar Szilveszter m@il me