Possible in xpath to have a conditional string-join or concat?

1.3k views Asked by At

I'm trying to do a conditional string join and wonder if there is something better than using an if statement.

The xml looks similar to

<office>
    <department>Math</department>
    <room>210</room>
</office>

The room tag is optional. If the room tag exists, I want to get a value like 'Math/210', otherwise just 'Math'.

I'm using string-join(('//office/department', '//office/room'), '/') but that then selects 'Math/' when the room tag doesn't exist.

I can get it to work the way I want if I do

if(exists('//office/room') then string-join(('//office/department', '//office/room'), '/') else '//office/department'

Is that the only way to do it or is there a better (cleaner) solution?

1

There are 1 answers

0
Michael Kay On

I'm using string-join(('//office/department', '//office/room'), '/') but that then selects 'Math/' when the room tag doesn't exist.

The quotes here are obviously wrong. It should be

string-join((//office/department, //office/room), '/')

or more concisely

//office/string-join((department, room), '/')

This should give you what you want, assuming the room element really doesn't exist. If "room" selects an empty sequence, there should be no separator. Of course if room does exist and contains a zero-length string, that's a different matter.