2012-03-30 92 views
-3

鉴于下面的XML,如果有任何作者来自美国,我需要解析它并输出所有书籍和作者姓名。使用LINQ解析XML

<?xml version="1.0" encoding="iso-8859-1"?> 
<bookstore> 
    <categories> 
    <category>Cooking</category> 
    <category>Children</category> 
    <category>Fiction</category> 
    </categories> 
    <books> 
    <book> 
     <title>Everyday Italian</title> 
     <authors> 
     <author> 
      <name>Giada De Laurentiis</name> 
      <country>USA</country> 
     </author> 
     </authors> 
     <price>30.00</price> 
    </book> 
    <book> 
     <title>XQuery Kick Start</title> 
     <authors> 
     <author> 
      <name>James McGovern</name> 
      <country>Sweden</country> 
     </author> 
     <author> 
      <name>Per Bothner</name> 
      <country>USA</country> 
     </author> 
     </authors> 
     <price>49.99</price> 
    </book> 
    </books> 
</bookstore> 

我该怎么做?

回答

2
var doc = XDocument.Parse(@"Your giant xml string here"); 
var books = 
    doc 
     .Descendants("book") 
     .Select(bookElement => 
     new 
     { 
      Title = bookElement.Descendants("title").Single().Value, 
      Authors = bookElement.Descendants("author") 
       .Where(authorElement => authorElement.Descendants("country").Single().Value == "USA") 
       .Select(authorElement => authorElement.Descendants("name").Single().Value) 
     }); 

foreach(var book in books) 
{ 
    Console.WriteLine("Book: " + book.Title); 
    Console.WriteLine("Authors: " + string.Join(",", book.Authors)); 
} 
+0

谢谢詹姆斯,解决了它 – James 2012-03-31 08:28:32