Linq to XML读取外部节点

时间:2011-06-03 11:24:03

标签: linq-to-xml

请有人请告诉我如何使用Linq to XML读取下面的外部节点,

<Root>
<ItemDetail>
      <UnitPrice>
        <Money currency="NZ">32</Money>
      </UnitPrice>
      <Description xml:lang="en">abc description</Description>
      <UnitOfMeasure>CU</UnitOfMeasure>
      <Classification domain="N/A"/>
      <ManufacturerPartID>12345678</ManufacturerPartID>
      <Extrinsic name="StockCode">23333</Extrinsic>
      <Extrinsic name="Quantity">1</Extrinsic>
 </ItemDetail>
<ItemDetail>
      <UnitPrice>
        <Money currency="NZ">32</Money>
      </UnitPrice>
      <Description xml:lang="en">abc description</Description>
      <UnitOfMeasure>CU</UnitOfMeasure>
      <Classification domain="N/A"/>
      <ManufacturerPartID>12345678</ManufacturerPartID>
      <Extrinsic name="StockCode">23333</Extrinsic>
      <Extrinsic name="Quantity">1</Extrinsic>
 </ItemDetail>
<ItemDetail>
      <UnitPrice>
        <Money currency="NZ">32</Money>
      </UnitPrice>
      <Description xml:lang="en">abc description</Description>
      <UnitOfMeasure>CU</UnitOfMeasure>
      <Classification domain="N/A"/>
      <ManufacturerPartID>12345678</ManufacturerPartID>
      <Extrinsic name="StockCode">23333</Extrinsic>
      <Extrinsic name="Quantity">1</Extrinsic>
 </ItemDetail>
</Root>

1 个答案:

答案 0 :(得分:1)

您想要达到什么目标?每个ItemDetail元素似乎都有两个Extrinsic子元素。你想同时访问它们吗?

var data = from item in XElement.Load("file.xml").Elements("ItemDetail")
           select new {
              stockcode = (int)item.Elements("Extrinsic").First(e => e.Attribute("name").Value == "StockCode"),
              quantity = (int)item.Elements("Extrinsic").First(e => e.Attribute("name").Value == "Quantity")
           };

我不确定股票代码是否为整数,但当然您可以改为使用字符串值(即(string)而不是(int))。