Search code examples
xmlxpathxpath-2.0

Help turning xpath result into formatted string


I am trying to parse an xml feed using xpath. The feed contains categories that look like this:

<categories>
<category id="6">Category 6</category>
<category id="12">Category 12</category>
<category id="19">Category 19</category>
</categories>

I currently using the path 'categories' to select all child nodes of which returns "Category 6Category 12Category 19" in string format. I would like the output to be like "Category 6, Category 12, Category 19" instead. How can I achieve this? I looked at xpath functions but nothing seems to fit this task.

I'm using this with Drupal's xpath parser module


Solution

  • Pure XPath is:

    concat(categories/category[id="6"],', ',
           categories/category[id="12"],', ',
           categories/category[id="19"])
    

    But it's not going to be very useful if you need something dynamic, I mean if you don't know categories children a priori.

    For a dynamic selection use:

    string-join(categories/*,', ')
    

    or

    string-join(/categories/*,', ')
    

    depending on the context.