Search code examples
xmlif-statementxpathnodes

XPath that selects a second element if the first element is blank


I have some XML that sometimes looks like this:

<object>
    <item>
        <name>Item Name</name>
    </item>
 </object>

And then can sometimes lack the Name element and have another name:

<object>
    <item>
        <name/>
        <altname>Item Name 2</altname>
    </item>
 </object>

The logic behind what I need is:

If has a value, use that. If it doesn't, use .

I tried adapting what I found here:

XPath: Default to 'Node A', select 'Node B' instead if 'Node B' is not empty

But to no avail... any ideas?


Solution

  • With XPath-2.0 and above you can do this with

    if (item/name !='') then item/name else item/altname
    

    With XPath-1.0 only it's a bit more tricky, but this will work:

    item/name[. !=''] | item/altname[../name ='']