XmlDocument - list all elements?

1

I have a code XML similar to this:

<document>
   <elemento>

   </elemento>
</document>

and the following C # code: ( x is an XmlDocument)

for (int i = 0; i < x.ChildNodes.Count; i ++)
{
    var element = x.ChildNodes[i];
    Console.WriteLine("Elemento: " + element.Name);
}

It turns out that it only lists the first child of the element, in the document case and does not list the children of document . How can I list all elements of code XML , including children of children?

    
asked by anonymous 03.10.2017 / 23:42

1 answer

1

You can use XPath to select all nodes:

var todosOsNos = x.SelectNodes("//*");
for (int i = 0; i < todosOsNos.Count; i++)
{
    var element = todosOsNos[i];
    Console.WriteLine("Elemento: " + element.Name);
}

The expression //* means the following:

  • // means you should fetch an element at any level of the tree
  • * means that any element serves (that is, we are not specifying an element filter)

Together this means: get the elements, whatever they are, at any level of the tree.

    
04.10.2017 / 01:23