0

Considering the following XML

<xml>
  <tag/>
  <tag version="2.1"/>
</xml>

I want an XPath 1.0 expression that returns <tag version="2.1"/> if I search for version 2.1, and <tag/> if I search for version 2.2.

So far, I've tried

/xml/tag[@version = '%version%' or not(@version)]

where %version% is a string that can be either 2.1 or 2.2, but if %version% is 2.1, it returns both nodes.

1
  • 1
    Searching on 2.1 returns both, because in your xpath you do or not(@version) and that will result in the tag without the attribute. So it does not matter what you pass into %version%, because always <tag/> will be returned because of the or statement... What you are trying to achieve is not possible in one XPath statement. Should be solved in code Commented Oct 4, 2013 at 12:31

2 Answers 2

3

You can use something like this, using | (or)

    /xml[not(tag[@version="2.1"])]/tag[not(@version)] |
    /xml[tag[@version="2.1"]]/tag[@version="2.1"]
  • either xml doesn't have tags with version="2.1", then return tags with no version attribute
  • or, if xml does contain tags with version="2.1", return these

So that would be in your case

    /xml[not(tag[@version='%version%'])]
        /tag[not(@version)]
    |
    /xml[tag[@version='%version%']]
        /tag[@version='%version%']
Sign up to request clarification or add additional context in comments.

Comments

3

As xpath 2.0 (if relevant) alternative to very nice @paul answer you could use

if (/xml/tag[@version = '2.1']) then /xml/tag[@version = '2.1'] else /xml/tag[not(@version)] 

resp.

if (/xml/tag[@version = '%version%']) then /xml/tag[@version = '%version'] else /xml/tag[not(@version)] 

1 Comment

That's indeed a very nice alternative, unfortunately I can't use xpath 2.0. I've updated my question accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.