jwaliszko
jwaliszko

Reputation: 17074

XPath expression - help needed

I have sample XML like this:

<users>
    <user name="user1">
        <roles separator=",">ADM,USER</roles>
    </user>
    <user name="user2">
        <roles separator=",">ADM,GUEST</roles>
    </user>
    <user name="user3">
        <roles separator=",">READER,GUEST</roles>
    </user>
</users>

Is there any way to get all users who are in role GUEST using XPath expression ?

Upvotes: 2

Views: 390

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243569

Use:

/users/user/[roles[contains(concat(@separator, ., @separator), 
                            concat(@separator, 'GUEST', @separator)
                           )
                  ]
            ]

This selects all desired user nodes, regardless whether 'GUEST' is the only role or it is at the start, in the middle or at the end of the string.

Upvotes: 1

Oded
Oded

Reputation: 499272

This XPath expression will select all users whose roles node contains GUEST.

//user[contains(roles, 'GUEST')]

See the contains xpath function.

Upvotes: 1

Per T
Per T

Reputation: 2038

If you're able to use XSLT 2.0 I would suggest you to tokenize the string of roles. Using contains() is fine as long as you don't start having role names like "EXTERNALGUEST" or similar since it would match that aswell.

/users/user[tokenize(roles, roles/@separator) = 'GUEST']/@name

This XPath will tokenize the roles depending on the @separator and return the users which has this role.

Upvotes: 0

Related Questions