【问题标题】:How to use LINQ to query a complex XML document?如何使用 LINQ 查询复杂的 XML 文档?
【发布时间】: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 类?

标签: c# xml linq


【解决方案1】:

这是你需要的东西:

var ns = XNamespace.Get("xyz");

var productLineItems =
    xd
        .Root
        .Descendants(ns + "product-lineitem")
        .Select(xe => new ProductLineItem()
        {
            ProductId = (int)xe.Element(ns + "product-id"),
            NetPrice = (decimal)xe.Element(ns + "net-price"),
        })
        .ToList();

根据您的示例数据,我得到了这个:

【讨论】:

    猜你喜欢
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多