使用LINQ为xml遍历XML树的每一个元素遍历、元素、LINQ、xml

2023-09-03 05:03:17 作者:空心少年c·

我想遍历每个元素和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);
        }
    }
 

C linq to xml的多种条件查找

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);
        }
    }