Xpath expression with multiple predicates

后端 未结 4 1746
庸人自扰
庸人自扰 2020-12-14 00:01

I am trying to build a complex xpath expression which will answer the following condition.

From the XML data below, returns the User entity which:

相关标签:
4条回答
  • 2020-12-14 00:39

    Assuming users is the root:

    /users/user[login='user1' and name='User 1' 
                and (profile='admin' and profile='operator')]
    
    0 讨论(0)
  • 2020-12-14 00:49

    The following should do what you're after:

    /root/user[login='user1' and 
               name='User 1' and 
               profile='admin' and
               profile='operator']
    

    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.

    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.

    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']]
    
    0 讨论(0)
  • 2020-12-14 00:59

    Here is a more exact answer (at present Greg Beech's answer does not check for condition 3. in the problem: the user element must have exactly 2 profile children):

    /*/user
            [login='user1' 
            and            
             name='User 1' 
            and  
             not(profile[3])
            and          
             profile/value='admin' 
            and           
             profile/value='operator'
             ]
    
    0 讨论(0)
  • 2020-12-14 01:02
    /root/user[login='user1' and name='User 1' and profile/value='admin' and profile/value='operator'
    
    0 讨论(0)
提交回复
热议问题