Jump to content

Transforming comma separated Strings to elements


Guest moyo333
 Share

Recommended Posts

Hello,I have a quite tricky problem with xslt and xpathThe following elements:<itemB refs="F1,F2" />should be transformed into this:<otherItem>F1</otherItem><otherItem>F2</otherItem>The attribute "refs" of "item" was defined as a String in the XML Schema.Can anyone help me with this please.

Link to comment
Share on other sites

That would be quite hard, if not impossible in XSLT 1.0 without using EXSLT's tokenize() extension function. In XSLT 2.0, there's a built in function for that, again called tokenize().

Link to comment
Share on other sites

I came up with I believe to be a solution that will handle any number of items in the refs attribute (F1,F2,F3, etc...). It uses a recursive template to process each item (up to the comma) and then passes the remaining value back to itself (after removing the part it had already processed). The last one, without an ending comma, is handled by the otherwise. Works fine under XSLT 1.0, no extensions needed

<xsl:stylesheet  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0">	<xsl:output method="xml"/>	<xsl:template match="/">		<xsl:apply-templates select="//itemB"/>	</xsl:template>	<xsl:template match="itemB">		<xsl:call-template name="DoRefs">			<xsl:with-param name="refs" select="@refs" />		</xsl:call-template>	</xsl:template>			<xsl:template name="DoRefs">		<xsl:param name="refs" />				<xsl:choose>			<xsl:when test="contains($refs,',')">				<otherItem><xsl:value-of select="substring-before($refs,',')"/></otherItem>				<xsl:call-template name="DoRefs">					<xsl:with-param name="refs" select="substring-after($refs,',')"/>				</xsl:call-template>			</xsl:when>			<xsl:otherwise>				<otherItem><xsl:value-of select="$refs"/></otherItem>			</xsl:otherwise>		</xsl:choose>			</xsl:template></xsl:stylesheet>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...