Maxqueue
Maxqueue

Reputation: 2454

C# Get all nodes in xml document but ignoring nested nodes

I have an xml document where i need to iterate over all nodes that are direct descendants of the parent.

For example i have the following xml document

<root>
  <node1>val1</node1>
  <node2>val2</node2>
  <nodes>
    <nestedNode>nestedvalue</nestedNode>
  </nodes>
</root>

I have the following code which gets me all the elements:

XmlNodeList nodes = doc.SelectNodes("//*");

This returns node1, node2, and nestedNode. What i want is only node1 and node2 and to ignore any nested values.

Thanks in advance for any help.

Upvotes: 3

Views: 201

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134521

To select elements that are children of the root element you would use the xpath:

/root/*

or in general:

/*/*

You should not traverse the all descendants here (//...) as that will go through all elements in the document. You would have to add additional filtering which would make the query unnecessarily complicated:

//*[parent::*[not(parent::*)]]

However, you want to filter out elements that do not have other child elements so you need to add the condition not(*):

/*/*[not(*)]

Upvotes: 5

Related Questions