【发布时间】:2016-06-08 16:03:04
【问题描述】:
我是使用 XML 和 LINQ 的新手,但我想要实现的是将此 XML 转换为具有两个字段的“product-lineitem”类型列表,一个用于净价格,一个用于产品-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;
}
}
【问题讨论】:
-
如果有多个相同
product-id的订单怎么办?你可以把它们分开吗?如果是这样,听起来您只需要root.Descendants("product-lineitem")即可将它们全部选中。目前尚不清楚您为什么要使用StringBuilder做任何事情,或者列表将是什么 of - 您是否在某处定义了LineItem类?