Matthew Hui
Matthew Hui

Reputation: 3361

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

Upvotes: 2

Views: 2971

Answers (3)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243449

In the general case of statically unknown XML document the wanted result cannot be produced using only pure XPath 1.0 -- some help from the programming language that is hosting it is needed.

A simple and pure XPath 2.0 solution for this is:

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

Upvotes: 1

Emiliano Poggi
Emiliano Poggi

Reputation: 24826

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.

Upvotes: 2

Alex Netkachov
Alex Netkachov

Reputation: 13522

In general, you should use the /categories/category xpath to select the category nodes and then enumerate the nodeset and display the content of each node, followed by the comma (except the last node). The exact code depends on the technology you use.

Upvotes: 1

Related Questions