簡體   English   中英

基於2個元素的XML linq查詢

[英]Xml linq query based on 2 Elements

如何使用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();

或使用基於方法的查詢:

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

您可以使用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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM