C#获取xml文档中的所有节点,但忽略嵌套节点

时间:2021-07-02 20:23:16

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

我有一个xml文档,我需要迭代所有父节点的直接后代节点。

For example i have the following xml document

例如,我有以下xml文档

<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.

这将返回node1,node2和nestedNode。我想要的只是node1和node2,并忽略任何嵌套值。

Thanks in advance for any help.

在此先感谢您的帮助。

1 个解决方案

#1


5  

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

要选择作为根元素的子元素的元素,您将使用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(*):

/*/*[not(*)]

#1


5  

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

要选择作为根元素的子元素的元素,您将使用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(*):

/*/*[not(*)]