Xmldocument - list all elements?

Asked

Viewed 180 times

1

I have a code XML similar to this :

<document>
   <elemento>

   </elemento>
</document>

and the following code C#: (x is a Xmldocument)

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

Turns out he only lists the first child of the element, in which case document and does not list the children of document. How can I list all elements of the code XML, including children of children?

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 search for an element at any level of the tree
  • * means any element serves (i.e., we are not specifying an element filter)

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.