我的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
?
答案 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");