【发布时间】:2011-08-02 15:47:41
【问题描述】:
所以,我不知道如何真正表达这个问题。我想要一个节点列表,并且只选择一个节点,而不是嵌套节点。例如:
<root>
<my_element>
<my_element>
Some Text
</my_element>
</my_element>
</root>
我知道我已经可以使用这个 xpath 做一些我想做的事情了:
Context: /
xPath: descendant::my_element[not(ancestor::my_element)]
哪个会返回这个结果集:
<root>
[<my_element>]
<my_element>
Some Text
</my_element>
[</my_element>]
</root>
这是我想要的预期行为。但我希望能够将上下文更改为:
/my_element
并得到这个结果集:
<root>
<my_element>
[<my_element>]
Some Text
[</my_element>]
</my_element>
</root>
我已经尽我所能查看 xPath 文档,但我没有想出任何东西。也许这里有人可以提供一些见解?
谢谢!
编辑 - 我希望能够选择一个 my_element 后代,它不是 my_element 的祖先,不包括上下文节点。
再次编辑 - 进一步解释。
我想要一个 xpath 查询来选择 my_element 的节点,只要该节点不是 my_element 的子节点。但是,如果 xpath 上下文设置为 my_element 节点,那么我不希望该节点计入表达式。因此 xpath 将匹配下一个 my_element 节点,即使它实际上是 my_element 的子节点。
- 再次编辑 -
这里还有一些例子。
<root>
<a>
<a>
<b>
<a>
Hello!
</a>
</b>
<a>
<b>
Hello Again
<a>
Sub
</a>
</b>
</a>
</a>
</a>
</root>
Context: /root/
Desire: Want to grab all A nodes, so long as they aren't a descendant of A
Result:
<root> == Context
[<a>]
<a>
<b>
<a>
Hello!
</a>
</b>
<a>
<b>
Hello Again
<a>
Sub
</a>
</b>
</a>
</a>
[</a>]
</root>
Context: /root/a/
Desire: Want to grab all A nodes, so long as they aren't a descendant of A, not including the context /root/a/
Result:
<root>
<a> == Context
[<a>]
<b>
<a>
Hello!
</a>
</b>
<a>
<b>
Hello Again
<a>
Sub
</a>
</b>
</a>
[</a>]
</a>
</root>
Context: /root/a/a/
Desire: Want to grab all A nodes, so long as they aren't a descendant of A, not including the context /root/a/a/
Result:
<root>
<a>
<a> == Context
<b>
[<a>]
Hello!
[</a>]
</b>
[<a>]
<b>
Hello Again
<a>
Sub
</a>
</b>
[</a>]
</a>
</a>
</root>
Context: /root/a/a/a/
Desire: Want to grab all A nodes, so long as they aren't a descendant of A, not including the context /root/a/a/a/
Result:
<root>
<a>
<a>
<b>
<a>
Hello!
</a>
</b>
<a> == Context
<b>
Hello Again
[<a>]
Sub
[</a>]
</b>
</a>
</a>
</a>
</root>
我希望这能让我的愿望更加清晰。感谢所有努力的人!
【问题讨论】:
-
@Kyle:这些不只是
my_element孩子吗?除非你想要一个my_element后代,它没有my_element祖先,不包括上下文节点及其祖先。 -
你的后者是正确的。我希望能够选择一个 my_element 后代,它不是 my_element 的祖先,不包括上下文节点。
-
@Kyle:我认为你不能在 XPath 1.0 中因为需要引用上下文节点。
-
@Alejandro:如果我将上下文放在 xpath 中并在那里进行检查,是否有可能?即:/my_element/descendant::my_element[not(ancestor::my_element)]
-
@Kyle:不。我能想到的唯一表达式是
./descendant::my_element[1],它选择第一个后代(那时它不会有my_element祖先)但它不会选择其余的my_element在其他上下文节点子分支中。