Skip to main content
 首页 » 编程设计

c#之如何使用 LINQ 查询复杂的 XML 文档

2024年02月05日12zdz8207

我是使用 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; 
        } 
} 

请您参考如下方法:

这是你需要的东西:

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(); 

根据您的样本数据,我得到了这个: