使用LINQ为xml遍历XML树的每一个元素 [英] traverse every element in xml tree using linq to xml
问题描述
我想遍历每个元素和XML属性,并抓住这个名字不知道元素的名称预先的价值。我甚至有一本关于LINQ为XML的C#和它只是告诉我如何查询来获取元素的值时,我已经知道了元素的名称。
只有以下的code给我的最高水平元素信息。我还需要达到全部下降元素。
的XElement reportElements = NULL;
reportElements = XElement.Load(filePathName.ToString());
的foreach(在reportElements.Elements的XElement XE())
{
的MessageBox.show(xe.ToString());
}
元素
只能走一个级别; 后代
遍历整个DOM的元素,然后你就可以(每件)检查属性:
的foreach(VAR EL在doc.Descendants()){
Console.WriteLine(el.Name);
的foreach(在el.Attributes变种ATTRIB()){
Console.WriteLine(>中+ attrib.Name +=+ attrib.Value);
}
}
I would like to traverse every element and attribute in an xml and grab the name an value without knowing the names of the elements in advance. I even have a book on linq to xml with C# and it only tells me how to query to get the value of elements when I already know the name of the element.
The code below only gives me the most high level element information. I need to also reach all of the descending elements.
XElement reportElements = null;
reportElements = XElement.Load(filePathName.ToString());
foreach (XElement xe in reportElements.Elements())
{
MessageBox.Show(xe.ToString());
}
Elements
only walks one level; Descendants
walks the entire DOM for elements, and you can then (per-element) check the attributes:
foreach (var el in doc.Descendants()) {
Console.WriteLine(el.Name);
foreach (var attrib in el.Attributes()) {
Console.WriteLine("> " + attrib.Name + " = " + attrib.Value);
}
}
这篇关于使用LINQ为xml遍历XML树的每一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!