简体   繁体   中英

Xml linq query based on 2 Elements

How can I return all the "Title" values for a particular 'Author' using 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>
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();

or using method-based query:

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

You can use 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM