开发者

XPath to convert child elements to single line list

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&g开发者_如何学Ct;
  <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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜