tags:

views:

25

answers:

1

I need XPath code to take child elements (one or more) and put them on a single line, separated by commas.

So if I have the following XML:

<Authors>
  <Author>Bob Smith</Author>
  <Author>Mary Jones</Author>
  <Author>Sam Doe</Author>
</Authors>

I want the following output:

Bob Smith, Mary Jones, Sam Doe

It needs to be smart enough to leave of the comma of the last author. And there might be only one author.

Much thanks

+1  A: 

XPath isn't a transformation tool so you can't use it alone to do what you want. You might be thinking of XSL, which uses XPath and is capable of transforming data.

An XPath expression that can pull data from your XML example would be

/Authors/Author

Then in whatever it is that you're using to execute the XPath expression on the document (be it XSL or some XML library) you can loop over the result and create the output you need.

In XSL you could do something along these lines:

<xsl:for-each select="/Authors/Author">
  <xsl:if test="position() != 1">
    <xsl:text>, </xsl:text>
  </xsl:if>
  <xsl:value-of select="text()"/>
</xsl:for-each>

Other languages would be more straightforward, likely using the language's join function, if it has one.

Welbog
It occurs to me that you might be talking about the XPath function `string-join`, which is available if you have XPath 2.0 at your disposal. In that case you can go with `string-join(/Authors/Author,', ')` to do what you want. Personally I don't like using XPath for string manipulation since it's so damned bad at it. But it is possible.
Welbog
@weblog: Xpath is not bad at all at string manipulation. C# still doesn't have a `translate()` function!. XPath 2.0 has Regex functions. So, what more do you need?
Dimitre Novatchev
@Dimitre: Really my gripe is with XPath 1.0. I'm just bitter.
Welbog
@weblog Yes, but fewer and fewer people use XPath 1.0 nowadays. I have been using XPath 2 for more than 6 years and I have developed a "compiler-compiler" - like system written entirely in XSLT 2.0. I have used this in producing parsers for JSON and for XPath 2.0.
Dimitre Novatchev