2012-03-30 11 views
-3

下記のXMLがあれば、著者のいずれかが米国出身の場合はすべての書籍とauthornameを解析して名前を出力する必要があります。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さん、ありがとうございました – James

関連する問題