2

我的 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然后execution_data使用 LINQ 从该订单中获取所有内容?

4

1 回答 1

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");
于 2013-07-14T17:20:58.867 回答