2012-03-30 198 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