gpt4 book ai didi

c# - LINQ:如何选择子节点满足条件的item元素?

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:20 27 4
gpt4 key购买 nike

我的 XML 看起来像这样:

 <order>
<order_number>1N</order_number>
<execution_data>
<exe_date>11/01/2011</exe_date>
<exe_name>Joe</exe_name>
</execution_data>
<execution_data>
<exe_date>12/01/2011</exe_date>
<exe_name>Mike</exe_name>
</execution_data>
<execution_data>
<exe_date>8/01/2011</exe_date>
<exe_name>Steve</exe_name>
</execution_data>
</order>
<order>
<order_number>2N</order_number>
<execution_data>
<exe_date>11/01/2011</exe_date>
<exe_name>Rob</exe_name>
</execution_data>
<execution_data>
<exe_date>12/01/2011</exe_date>
<exe_name>Marko</exe_name>
</execution_data>
<execution_data>
<exe_date>8/01/2011</exe_date>
<exe_name>Sam</exe_name>
</execution_data>
</order>
<order>
<order_number>3N</order_number>
<execution_data>
<exe_date>11/01/2011</exe_date>
<exe_name>Nick</exe_name>
</execution_data>
<execution_data>
<exe_date>12/01/2011</exe_date>
<exe_name>Ashley</exe_name>
</execution_data>
<execution_data>
<exe_date>8/01/2011</exe_date>
<exe_name>Marc</exe_name>
</execution_data>
</order>


public class ExecutionItem
{
public string Date {get;set;}
public string Name {get;set;}
}

public class Response
{
public List<ExecutionItem> ExecutionItems{get;set;}
}

如何选择 order_number 等于 1N 的订单,然后使用 LINQ 从该订单中获取所有 execution_data

最佳答案

嗯,这里有两种方法:

  • 你可以找到所有 <order_number>值为 1N 的元素,然后找到所有兄弟 execution_data元素
  • 你可以找到order具有相关元素的 order_number元素,然后找到 child execution_data元素。

我可能会选择后一种方法,类似于:

var executionDataElements = 
doc.Descendants("order")
.Where(order => (string) order.Element("order_number") == "1N")
.SelectMany(order => order.Elements("execution_data");

(请注意,如果这匹配了多个订单,您将从所有匹配订单中获取所有元素。)

第一种方法如果您知道 execution_data元素在 order_number 之后元素,如果你知道只有一个这样的 order_number元素,将是:

var executionDataElements = doc.Descendants("order_number")
.First(x => (string) x == "1N")
.ElementsAfterSelf("execution_data");

关于c# - LINQ:如何选择子节点满足条件的item元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17641720/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com