基于2个元素的Xml linq查询

时间:2014-01-11 00:24:25

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

如何使用linq返回特定“作者”的所有“标题”值?

<Details xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Record>
    <Author>Barry White</Author>
    <Title>First Book</Title>
  </Record>
  <Record>
    <Author>Barry White</Author>
    <Title>Second Book</Title>
  </Record>
  <Record>
    <Author>Norman White</Author>
    <Title>Second Book</Title>
  </Record>
 </Details>

2 个答案:

答案 0 :(得分:2)

var xDoc = XDocument.Load("Input.xml");

var author = "Barry White";
var titles = (from r in xDoc.Root.Elements("Record")
              let _author = (string)r.Element("Author")
              let _title = (string)r.Element("Title")
              where _author == author
              select _title).ToList();

或使用基于方法的查询:

var titles = xDoc.Root.Elements("Record")
                 .Where(r => (string)r.Element("Author") == author)
                 .Select(r => (string)r.Element("Title"))
                 .ToList();

答案 1 :(得分:2)

您可以使用LINQ to XML

var titles = XDocument.Parse(inputxml)
                      .Descendants("Record")
                      .Where(x => x.Element("Author").Value == "Barry White")
                      .Select(x => x.Element("Title").Value)
                      .ToList();