使用LINQ查询XDocument,如何获取具体值?

Using LINQ to query XDocument, how to get specific values?

我正在尝试重构以下内容 - 这行得通,但如果我开始在 XML 中获取更多元素,它将变得难以管理:

HttpResponseMessage response = await httpClient.GetAsync("https://uri/products.xml");

string responseAsString = await response.Content.ReadAsStringAsync();

List<Product> productList = new List<Product>();

XDocument xdocument = XDocument.Parse(responseAsString);
var products = xdocument.Descendants().Where(p => p.Name.LocalName == "item");

foreach(var product in products)
{
    var thisProduct = new Product();
    foreach (XElement el in product.Nodes())
    {
        if(el.Name.LocalName == "id")
        {
            thisProduct.SKU = el.Value.Replace("-master", "");
        }
        if (el.Name.LocalName == "availability")
        {
            thisProduct.Availability = el.Value == "in stock";
        }
    }
    productList.Add(thisProduct);
}

给定以下 XML URL

<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
    xmlns="http://base.google.com/ns/1.0" version="0">
    <channel>
        <title>Product Feed</title>
        <link></link>
        <description>Products</description>
        <item>
            <availability>in stock</availability>
            <id>01234-master</id>
            ...
        </item>
        <item>
            <availability>in stock</availability>
            <id>abcde-master</id>
            ...
        </item>
    </channel>
</rss>

理想情况下,我想删除循环和 if 语句,并有一个 LINQ 查询 returns 只有我需要的字段(id、可用性等)来自 XML干净利落的方式,并用这些数据填充一个简单的 class。

有人可以帮忙吗?

尝试以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            new Item(FILENAME);

        }
    }
    public class Item
    {
        public static List<Item> items { get; set; }

        public string availability { get; set; }
        public string id { get; set; }

        public Item() { }
        public Item(string filename)
        {
            string xml = File.ReadAllText(filename);

            XDocument doc = XDocument.Parse(xml);
            XElement root = doc.Root;
            XNamespace ns = root.GetDefaultNamespace();

            Item.items = doc.Descendants(ns + "item").Select(x => new Item() {
                availability = (string)x.Element(ns + "availability"),
                id = (string)x.Element(ns + "id")
            }).ToList();
        }
    }
}

有时候不得不为自己写的代码感到高兴。有时候没有"smarter"的写法...只能写一点"better":

List<Product> productList = new List<Product>();

XDocument xdocument = XDocument.Parse(responseAsString);

XNamespace ns = "http://base.google.com/ns/1.0";

var products = from x in xdocument.Elements(ns + "rss")
               from y in x.Elements(ns + "channel")
               from z in y.Elements(ns + "item")
               select z;

foreach (var product in products)
{
    var prod = new Product();
    productList.Add(prod);

    foreach (XElement el in product.Elements())
    {
        if (el.Name == ns + "id")
        {
            prod.SKU = el.Value.Replace("-master", string.Empty);
        }
        else if (el.Name == ns + "availability")
        {
            prod.Availability = el.Value == "in stock";
        }
    }
}

备注:

  • Descendants() 在道德上是错误的。 item 有一个固定的位置,/rss/channel/item,你非常清楚。它不是 //item。因为明天可能会有今天不存在的 rss/foo/item。您尝试编写代码,使其与可以添加到 xml.
  • 的附加信息向前兼容
  • 我讨厌 xml 命名空间...还有 xml 具有多个嵌套的命名空间。我多么讨厌那些。但是比我更聪明的人认为它们存在。我接受。我用它们编码。在 LINQ-to-XML 中,这很容易。有一个 XNamespace 甚至有一个重载的 + 运算符。

    注意,如果你是微优化(我尽量不是,但我不得不承认,但我的手有点痒),你可以预先计算出各种ns + "xxx"for 循环中使用,因为从这里看不清楚,但它们在每个循环中都会重建。 XName 是如何在内部构建的……哦……这是一件令人着迷的事情,相信我。

    private static readonly XNamespace googleNs = "http://base.google.com/ns/1.0";
    private static readonly XName idName = googleNs + "id";
    private static readonly XName availabilityName = googleNs + "availability";
    

    然后

    if (el.Name == idName)
    {
        prod.SKU = el.Value.Replace("-master", string.Empty);
    }
    else if (el.Name == availabilityName)
    {
        prod.Availability = el.Value == "in stock";
    }