XPath :选择所有后续兄弟姐妹,直到另一个兄弟姐妹 [英] XPath : select all following siblings until another sibling
问题描述
这是我的 xml 的摘录:
<节点/><node id="1">content</node><节点/><节点/><节点/><node id="2">content</node><节点/><节点/>
我位于 node[@id='1']
.我需要一个 Xpath 来匹配所有
元素,直到下一个非空节点(此处为 node[@id='2']
).
@id 属性只是为了更清楚地解释我的问题,而不是在我原来的 XML 中.我需要一个不使用 @id 属性的解决方案.
<小时>我不想想要匹配 node[@id='2']
之后的空兄弟,所以我不能使用简单的 following-兄弟::节点[text()='']
.
我怎样才能做到这一点?
你可以这样做:
<预>../node[not(text()) 和previous-sibling::node[@id][1][@id='1']]其中'1'
是当前节点的id(动态生成表达式).
表达式说:
- 从当前上下文转到父级
- 选择那些子节点
- 没有文字和
- 从所有具有 id 的前面同级节点"中,第一个的 id 必须为 1
如果您使用 XSLT,则可以从以下兄弟轴中进行选择,因为您可以使用 current()
函数:
<xsl:for-each select="node[@id='1']"><xsl:copy-of select="跟随兄弟::节点[不(文本())和生成 id(preceding-sibling::node[@id][1])=生成 ID(当前())]"/></xsl:for-each>
或更简单(也更有效)的键:
Here is an excerpt of my xml :
<node/>
<node/>
<node id="1">content</node>
<node/>
<node/>
<node/>
<node id="2">content</node>
<node/>
<node/>
I am positioned in the node[@id='1']
. I need an Xpath to match all the <node/>
elements until the next not empty node (here node[@id='2']
).
Edit: the @id attributes are only to explain my problem more clearly, but are not in my original XML. I need a solution which does not use the @id attributes.
I do not want to match the empty siblings after node[@id='2']
, so I can't use a naive following-sibling::node[text()='']
.
How can I achieve this ?
You could do it this way:
../node[not(text()) and preceding-sibling::node[@id][1][@id='1']]
where '1'
is the id of the current node (generate the expression dynamically).
The expression says:
- from the current context go to the parent
- select those child nodes that
- have no text and
- from all "preceding sibling nodes that have an id" the first one must have an id of 1
If you are in XSLT you can select from the following-sibling axis because you can use the current()
function:
<!-- the for-each is merely to switch the current node -->
<xsl:for-each select="node[@id='1']">
<xsl:copy-of select="
following-sibling::node[
not(text()) and
generate-id(preceding-sibling::node[@id][1])
=
generate-id(current())
]
" />
</xsl:for-each>
or simpler (and more efficient) with a key:
<xsl:key
name="kNode"
match="node[not(text())]"
use="generate-id(preceding-sibling::node[@id][1])"
/>
<xsl:copy-of select="key('kNode', generate-id(node[@id='1']))" />
这篇关于XPath :选择所有后续兄弟姐妹,直到另一个兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!