获取特定层级的元素 [英] Get elements of specific hierarchy level
问题描述
有没有办法使用 XPath 检索特定层次结构级别的所有元素?
Is there any way to retrieve all elements of specific hierarchy level using XPath?
更新.
<A>
<B>1</B>
<B>2</B>
</A>
<C>
<D>3</D>
<D>4</D>
</C>
我需要检索所有 B 和 D 元素(层次级别 = 2)
I need to retrieve all B and D elements (hierarchy level = 2)
推荐答案
您的示例缺少根元素,因此我假设如下:
Your example lacks a root element, so I assume something like this:
<ROOT>
<A>
<B>1</B>
<B>2</B>
</A>
<C>
<D>3</D>
<D>4</D>
</C>
</ROOT>
有了这个,一个简单的版本就是使用适当数量的任何元素"通配符来获得结果:
With this, a simple version would be to just use the appropriate number of 'any element' wildcards to get your result:
xpath = '/*/*/*'
(意思是'选择任意根元素的任意子元素的任意子元素')
(Meaning 'select any child element of any child element of any root element')
或者,如果您想用数字表示级别,可以使用:
Alternatively, if you want to express the level numerically, you could use:
xpath = '//*[count(ancestor::*) = 2]'
(意思是选择任何具有 2 个祖先的元素")
(Meaning 'select any element with 2 ancestors')
编辑/注意:正如 Dimitre Novatchev 正确指出的,区分节点和元素很重要,我修正了我的答案因此.(虽然元素本身就是节点,还有六种其他类型的节点!)
Edit/Note: As Dimitre Novatchev correctly pointed out, it is important to differentiate between nodes and elements, and I fixed my answer accordingly. (While elements are nodes themselves, there are also six other types of nodes!)
通过将基于祖先的 xpath 稍微更改为:
The difference can be illustrated with the given example by altering the ancestor based xpath slightly to:
xpath = '//*[count(ancestor::node())=2]'
这将选择 A 和 B,因为根元素将算作一个祖先节点,而根节点 '/' 算作另一个!
This would select A and B, as the root element would count as one ancestor node, and the root node '/' as another!
这篇关于获取特定层级的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!