我有一个结构如下的XML文档:
<dipOrders>
<interchangeInfo senderEdiCode="LSC58" senderEdiCodeQal="ZZ" receiverEdiCode="15274" receiverEdiCodeQal="ZZ" syntax="X12" syntaxId="X" syntaxVersion="003010"/>
<order orderNumber="219299" orderDate="2012-12-05T00:00:00" validityDate="2012-12-05T00:00:00">
<buyer name="LEAR MTO">
<partyCode buyerCode="811567924"/>
</buyer>
<supplier name="BRIDGE OF WEIR LEATHER CO">
<partyCode buyerCode="749630"/>
</supplier>
<orderConsignee name="LEAR MEXICAN SEATING CORP">
<partyCode buyerCode="LSC59"/>
<orderLine description="LEA DC 378 HERO 6RSB 5B8" orderNumber="246767" engineeringChangeNumber="N">
<partyCode buyerCode="DC378105H6RSB5B8AA"/>
<cumulativeQuantity date="2012-12-04T00:00:00" quantity="0"/>
<orderQuantity quantity="0" commitmentLevel="Firm" timingQualifier="Weekly" shipDate="2012-12-05T00:00:00"/>
</orderLine>
<orderLine description="LEA DC 378 HERO 6RSB 5V0" orderNumber="246767" engineeringChangeNumber="N">
<partyCode buyerCode="DC378105H6RSB5V0AA"/>
<cumulativeQuantity date="2012-12-04T00:00:00" quantity="0"/>
<orderQuantity quantity="0" commitmentLevel="Firm" timingQualifier="Weekly" shipDate="2012-12-05T00:00:00"/>
<orderQuantity quantity="600" commitmentLevel="Firm" timingQualifier="Weekly" shipDate="2012-12-06T00:00:00"/>
</orderLine>
这是我如何访问orderLine项目的属性:
List<int> orderNumbers = doc.Descendants("orderLine").Select(x => int)x.Attribute("orderNumber")).ToList();
List<string> descriptions = doc.Descendants("orderLine").Select(x => (string)x.Attribute("description")).ToList();
List<string> buyerCodes = doc.Descendants("orderLine").Select(x => (string)x.Element("partyCode").Attribute("buyerCode")).ToList();
然而,orderLine可以有不同数量的orderQuantity节点。我如何在Linq语句中解决它,以获得orderLine和orderQuantity之间的适当关系?
您可以通过使用
获取orderQuantity元素var data = doc.Descendants("orderLine").
Descendants("orderQuantity")
.Select(x => new {paernt = x.Parent, x}).ToList();
也这样做
var data = doc.Descendants("orderLine").
Descendants("orderQuantity")
.Select(x => new {OrderNumber= (int) x.Parent.Attribute("orderNumber"),
x}).ToList();
尝试在下一个示例中使用SelectMany
var r = doc.Descendants("orderLine")
.SelectMany(node => node.Elements("orderQuantity")
.Select(el => new {OrderNumber = (int)node.Attribute("orderNumber"), Quantity = (int)el.Attribute("quantity")}));
现在您有一个匿名对象序列,指示订单号和相应的数量,如:
246767 0
246767 600