1
有人可以幫助我如何閱讀下面的XML文檔使用Linq XML?LINQ to XML - 讀取XML文檔
<?xml version='1.0' encoding='UTF-8' ?>
<cXML>
<Request>
<OrderRequest>
<OrderRequestHeader orderID="xy1234" orderDate="2007-01-1T15:5400+10:00" type="new" orderVersion="001">
<Total>
<Money currency="NZ">34.06</Money>
</Total>
<ShipTo>
<Address>
<Name xml:lang="en">xyz</Name>
<PostalAddress name="xyz">
<Street>xyz street</Street>
<City>xyz</City>
</PostalAddress>
</Address>
</ShipTo>
<BillTo>
<Address>
<Name xml:lang="en">XYZ</Name>
<PostalAddress name="XYZ">
<Street>PO BOX 1234</Street>
<City>xyz</City>
<State>xyz state</State>
</PostalAddress>
</Address>
</BillTo>
<Contact role="xxx" addressID="123456789">
<Name xml:lang="en">XYZ</Name>
<Email name="business">[email protected]</Email>
<Phone>
<TelephoneNumber>
<Number>1234-1234</Number>
</TelephoneNumber>
</Phone>
</Contact>
<Contact role="ShipTo">
<Name xml:lang="en">XYZ</Name>
</Contact>
<Contact role="Supplier">
<Name xml:lang="en">XYZ pty ltd</Name>
</Contact>
</OrderRequestHeader>
<ItemOut quantity="20" lineNumber="1" requestedDeliveryDate="2007-01-01T00:0000+10:00">
<ItemID>
<SupplierPartID>12345678</SupplierPartID>
</ItemID>
<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">12345</Extrinsic>
<Extrinsic name="Quantity">1</Extrinsic>
</ItemDetail>
</ItemOut>
<ItemOut quantity="10" lineNumber="2" requestedDeliveryDate="2007-01-01T00:0000+10:00">
<ItemID>
<SupplierPartID>12345678</SupplierPartID>
</ItemID>
<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>
</ItemOut>
</OrderRequest>
我試着用這個代碼,但它給空值或對象引用未設置錯誤:
XDocument xdoc = XDocument.Load(@"C:\PO.xml");
var itemOut = (from c in xdoc.Descendants("OrderRequest")
select new
{
SupplierID = c.Element("Money").Value ,
Currency = c.Attribute("currency").Value,
Money = c.Element("Money").Value,
Description = c.Element("Description").Value,
ManufacturerPartID = c.Element("ManufacturerPartID").Value,
Extrinsic = c.Attribute("name").Value
});
foreach (var element in itemOut)
{
Console.WriteLine(element.SupplierID);
}
Console.ReadLine();
非常感謝!想一想,這是獲取元素值的最佳方式,即必須執行c.Element(「ItemID」)。Element(「SupplierPartID」)。value? .NET無法弄清楚我們是否做c.Element(「SupplierPartID」)? – 2011-05-29 12:25:21
對不起,如果我們添加另一個4 .... 元素,那麼代碼會是什麼樣子,因爲這將是什麼樣子(即真正的xml文檔)。基本上,ItemOut元素對應於訂單項的數量。 –
2011-05-29 12:27:55
不管是否有零個,一個,兩個或多個「ItemOut」元素,well'from xdoc.Descendants(「ItemOut」)不會以任何方式改變。至於做'c.Element(「ItemID」)。Element(「SupplierPartID」)',如果你不喜歡逐級進行,那麼你可以使用'c.Descendants(「SupplierPartID」)。 。 – 2011-05-29 12:49:51