【问题标题】:Parsing XML using LINQ [closed]使用 LINQ 解析 XML [关闭]
【发布时间】:2012-03-30 18:48:27
【问题描述】:

鉴于下面的 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>

我该怎么做?

【问题讨论】:

    标签: c# .net linq linq-to-xml


    【解决方案1】:
    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));
    }
    

    【讨论】:

    • 谢谢詹姆斯,解决了它
    猜你喜欢
    • 2011-06-13
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    相关资源
    最近更新 更多