如何从XmlDocument对象获取XML元素?

use*_*554 5 .net c# xml linq xmldocument

假设使用以下代码成功加载了XmlDocument:

var doc = new XmlDocument();
doc.Load(stream);
Run Code Online (Sandbox Code Playgroud)

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

<ProductTable>
<ProductName>Chair</ProductName>
<Price>29.5</Price>
</ProductTable>
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*dam 9

我建议使用an 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);
}
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢使用糖衣SQL语法,或者想阅读相关主题,那么这篇MSDN文章是一个很好的起点.

如果您想使用匿名类型,以下是更简洁的版本:

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
    };
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用此表达式语法在控制台中打印匹配项:

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