【问题标题】:How to get XML Elements from XmlDocument object?如何从 XmlDocument 对象获取 XML 元素?
【发布时间】:2011-12-25 22:17:27
【问题描述】:

假设使用此代码成功加载了一个 XmlDocument:

var doc = new XmlDocument();
doc.Load(stream);

这是 XML 流的一个示例部分(完整的 XML 流有大约 10000 个 ProductTable):

<ProductTable>
<ProductName>Chair</ProductName>
<Price>29.5</Price>
</ProductTable>

使用 Linq,我如何访问 ProductName 和 Price 元素?谢谢。

【问题讨论】:

    标签: c# .net xml linq xmldocument


    【解决方案1】:

    我建议使用XDocument 而不是XmlDocument(后者不适合LINQ to XML)。使用XDocument.Load(...) 方法加载您的“真实”XML。

    string xml = @"<ProductTable>
    <ProductName>Chair</ProductName>
    <Price>29.5</Price>
    </ProductTable>";
    XDocument x = XDocument.Parse(xml);
    var tables = x.Descendants("ProductTable");
    Dictionary<string,string> products = new Dictionary<string, string>();
    foreach (var productTable in tables)
    {
        string name = productTable.Element("ProductName").Value;
        string price = productTable.Element("Price").Value;
        products.Add(name, price);
    }
    

    如果您更喜欢使用糖衣 SQL 之类的语法或想阅读该主题,this MSDN article 是一个很好的起点。

    如果您想使用anonymous type,以下是更简洁的版本:

    XDocument document = XDocument.Parse(xml)
    var products = /* products is an IEnumerable<AnonymousType> */
        from item in document.Descendants("ProductTable")
        select new
        {
            Name = item.Element("ProductName").Value,
            Price = item.Element("Price").Value
        };
    

    然后您可以使用这种富有表现力的语法在控制台中打印匹配项:

    foreach (var product in products) /* var because product is an anonymous type */
    {
        Console.WriteLine("{0}: {1}", product.Name, product.Price);
    }
    Console.ReadLine();
    

    【讨论】:

    • 非常感谢,codesparkle。我打算今晚晚些时候回家时试一试。我将在 12 月 25 日探亲,因此只能阅读您的答案而无法进行测试。
    • codesparkle:你真是个天才!您的代码完美运行。非常感谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2013-12-02
    • 2013-08-24
    • 1970-01-01
    相关资源
    最近更新 更多