Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
769 views
in Technique[技术] by (71.8m points)

xml - Xpath expression with multiple predicates

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:

  1. His loginname is "user1"
  2. His name is "User 1"
  3. 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?

EDIT: Added a complex profile entity

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...