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

时间:2011-12-25 22:17:27

标签: c# .net xml linq xmldocument

假设使用以下代码成功加载了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 个答案:

答案 0 :(得分: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语法,或想阅读相关主题,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();