0
votes

I have been struggling concatenating child node values using XPath.

We have an XML file with a parent node and three child nodes each, what I am trying to achieve is to get only two of these child nodes and concatenate their values as CHILDNODE1 [CHILDNODE2]

E.g. The parent node would look like this

  <Term>
    <ID>24</ID>
    <Code>abc</Code>
    <Name>xyz</Name>
  </Term>

XPath Call: Code[Name]

Result: abc[xyz]

Almost missed to mention, I am trying to get an ArrayList as outcome for all the similar nodes, i.e. Instead of looping over these nodes and concatenate one by one, get all these values in one XPath query (not sure that's even possible).

I would like to know if this is possible at all and some suggestions/examples would be really great.

If it cannot be achieved suing XPath then would be the other options.

1

1 Answers

1
votes

In XPath 1.0 (the only one natively supported by Java), this is only possible for single <Term/> elements per file/XPath call.

The XPath expression

concat(/Term/Code, '[', /Term/Name, ']')

will return exactly what you're looking for.

If there are multiple <Term/> nodes, you will have to fetch the <Term/> nodes with XPath (//Term), get the respective child nodes using DOM and construct the result set in Java.

With support for XPath 2.0 (for example by embedding Saxon, BaseX or other more powerful XPath/XQuery processors), you can also do this for an arbitrary number of <Term/> elements in one file (under a common parent node, of course):

for $term in //Term
return concat($term/code, '[', $term/name, ']')