简体   繁体   中英

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.

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(*)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM