LINQ:如何选择子节点满足条件的项元素?

时间:2013-07-14 17:17:47

标签: c# .net linq

我的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

1 个答案:

答案 0 :(得分:2)

嗯,这里有两种方法:

  • 您可以找到值为<order_number>的所有1N元素,然后找到所有同级execution_data元素
  • 您可以找到包含相关order元素的order_number元素,然后找到子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");