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

5

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

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

这是XML流的一个示例部分(完整的XML流大约有10000个ProductTable):
<ProductTable>
<ProductName>Chair</ProductName>
<Price>29.5</Price>
</ProductTable>

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

9

我建议使用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 语法,或者想了解更多相关知识,这篇 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
    };

您可以使用这种表达性语法将匹配项打印到控制台中:
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日拜访家人,所以只能阅读您的答案而无法测试。 - user763554
codesparkle:你绝对是个天才!你的代码完美地运行了。非常感谢!!! - user763554

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接