xmlxpath

Create a list with XPATH but not all nodes are available


I do have some weird XML I want to analyse:

<body>
<return>
  <items>
   <key>name</key>
   <value>A</value>
  </items>
  <items>
   <key>version</key>
   <value>1</value>
  </items>
</return>
<return>
  <items>
   <key>name</key>
   <value>B</value>
  </items>
</return>
</body>

As you can see: some "return" do have "items/value", some don't

I'd like an xpath expression where the output is something like

Name: A, Version: 1
Name: B, Version: n/a

I tried with both "map:merge" and ||

Yet I get cardinality error.

/*/return/items[key="name"]/value/string() ||/*/return/items[key="version"] 

Can I force /*/return/items[key="version"] to return "something" when the node is not found? So that I can get rid of the cardinality?

Maybe there's a totally different solution


Solution

  • Shouldn't need to use an if; just create a sequence of the version and a default value and use the first in the sequence.

    Not sure what version of XPath you're using, but this should work for 3.0+. (If you're using 2.0, you might need to replace the concat operators (||) with concat().)

    for $ret in //return return 'Name: ' || $ret/items[1]/value || ', Version: ' || ($ret/items[2]/value,'n/a')[1]