假设用以下代码成功加载了一个XmlDocument:
var doc = new XmlDocument();
doc.Load(stream);
这是XML流的一个示例部分(完整的XML流大约有10000个ProductTable):
<ProductTable>
<ProductName>Chair</ProductName>
<Price>29.5</Price>
</ProductTable>
使用 Linq,我如何访问 ProductName 和 Price 元素?谢谢。
假设用以下代码成功加载了一个XmlDocument:
var doc = new XmlDocument();
doc.Load(stream);
<ProductTable>
<ProductName>Chair</ProductName>
<Price>29.5</Price>
</ProductTable>
我建议使用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);
}
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();