[英]How to use LINQ to query a complex XML document?
我剛接觸XML和LINQ,但是我要實現的目標是將XML轉換為具有兩個字段的“ product-lineitem”類型列表,一個用於net-price,一個用於product-id。
所以在C#中
List<ProductLineItem>
還有像
public class ProductLineItem
{
public int ProductId {get;set;}
public decimal NetPrice {get;set;}
}
這是XML文件的示例
<?xml version="1.0" encoding="UTF-8"?>
<orders xmlns="xyz">
<order order-no="00000605">
<order-date>2016-04-25T13:45:14.133Z</order-date>
<created-by>storefront</created-by>
<original-order-no>00000605</original-order-no>
<product-lineitems>
<product-lineitem>
<net-price>57.75</net-price>
<product-id>3210</product-id>
</product-lineitem>
<product-lineitem>
<net-price>55.00</net-price>
<product-id>5543</product-id>
</product-lineitem>
<product-lineitem>
<net-price>57.75</net-price>
<product-id>4987</product-id>
</product-lineitem>
</product-lineitems>
</order>
<order order-no="00000622">
...
</order>
<order order-no="00000666">
...
</order>
</orders>
因此,理想情況下,我的最終結果將是抓取所有這些內容並創建上面定義的類的列表
<product-lineitem>
<net-price></gross-price>
<product-id></product-id>
</product-lineitem>
我正在努力弄清楚如何為此實現LINQ查詢。 我一直在使用XElement和StringBuilder,但希望有一個對象列表,而不是像下面的代碼那樣嘗試手動構建字符串。
XElement root = XElement.Load(fileName);
StringBuilder result = new StringBuilder();
result.AppendLine(element.Attribute("order-no").Value);
foreach (XElement orderElement in root.Elements())
{
result.AppendLine(orderElement.Attribute("order-no").Value);
foreach(var item in orderElement.Element("product-lineitems").Elements())
{
var i = item.Element("product-id").Value;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.