views:

552

answers:

2

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());
            }
+1  A: 

You should try:

reportElements.Descendants()
empi
+4  A: 

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);
        }
    }
Marc Gravell
This worked great! Thanks very much for the help!
JK
JK - Forgot something?
Rafe Lavelle
Er, I don't don't know what you mean by forgot something.
JK
@JK: Me neither...
Marc Gravell