具有多个谓词的 Xpath 表达式 [英] Xpath expression with multiple predicates
问题描述
我正在尝试构建一个复杂的 xpath 表达式,它将满足以下条件.
I am trying to build a complex xpath expression which will answer the following condition.
从下面的 XML 数据中,返回 User 实体:
From the XML data below, returns the User entity which:
- 他的登录名是user1"
- 他的名字是用户 1"
他有 2 个不同的配置文件值,分别是operator"和admin"(我不知道前面的确切顺序)
- His loginname is "user1"
- His name is "User 1"
He has 2 different profiles values which are "operator" and "admin" (I don't know the exact order ahead)
<user>
<login>user1</login>
<name>User 1</name>
<profile>
<value>admin</value>
<id>2</id>
<description>admin users</description>
</profile>
<profile>
<value>operator</value>
<id>1</id>
<description>Operator</description>
</profile>
</user>
<user>
<login>user2</login>
<name>User 2</name>
<profile>
<value>admin</value>
<id>4</id>
<description>admins users</description>
</profile>
<profile>
<value>poweruser</value>
<id>5</id>
<description>power users</description>
</profile>
</user>
</root>
有人可以为这种情况提供一个例子吗?
Can someone please supply an example for such a case?
添加了一个复杂的配置文件实体
推荐答案
以下应该满足您的需求:
The following should do what you're after:
/root/user[login='user1' and
name='User 1' and
profile='admin' and
profile='operator']
对 profile
值进行两次测试可能看起来很奇怪,但由于有多个 profile
节点,那么只要至少有一个节点与测试.
Having two tests for the profile
value might seem odd, but as there are multiple profile
nodes then the condition will be satisfied as long as at least one node matches the test.
您可以将 profile
直接与 string
进行比较的原因,即使它实际上是一个 node
是 string-一个元素节点的值
是其所有子节点的string-value
连接在一起,在这种情况下就是value
的内容.
The reason you can compare profile
directly to a string
, even though it actually is a node
is that the string-value
of an element node is the string-value
of all its descendants concatenated together, which in this case is just the contents of value
.
如果 profile
包含的元素多于 value
,则必须使用稍微复杂的谓词测试来确定是否存在匹配的 profile
仅基于 value
的节点(这应该适用于您更新的问题):
If profile
contained more elements than value
you'd have to use a slightly more complex predicate test to determine the existence of a matching profile
node based just on the value
(this should work with your updated question):
/root/user[login='user1' and
name='User 1' and
profile[value='admin'] and
profile[value='operator']]
这篇关于具有多个谓词的 Xpath 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!