Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

traverse every element in xml tree using 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());
            }
like image 431
JK. Avatar asked Nov 15 '09 21:11

JK.


1 Answers

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);
        }
    }
like image 167
Marc Gravell Avatar answered Sep 21 '22 10:09

Marc Gravell