简体   繁体   English

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

[英]How to get XML Elements from XmlDocument object?

Assume that an XmlDocument is successfully loaded with this code: 假设使用以下代码成功加载了XmlDocument:

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

This is a sample portion of the XML stream (the complete XML stream has about 10000 of ProductTable's): 这是XML流的示例部分(完整的XML流有大约10000个ProductTable):

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

Using Linq, how do I access the ProductName and Price elements? 使用Linq,如何访问ProductName和Price元素? Thanks. 谢谢。

I suggest using an XDocument instead of an XmlDocument (the latter is not suited for LINQ to XML). 我建议使用XDocument而不是XmlDocument (后者不适合LINQ to XML)。 Use the XDocument.Load(...) method to load your "real" 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);
}

If you'd prefer to use sugar-coated SQL like syntax or would like to read up on the topic, this MSDN article is a great place to start. 如果您更喜欢使用糖衣SQL语法,或者想阅读相关主题,那么这篇MSDN文章是一个很好的起点。

The following is a more concise version if you feel like using an 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
    };

You could then use this expressive syntax to print the matches in the console: 然后,您可以使用此表达式语法在控制台中打印匹配项:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM