问题
I have some data in an XML element that looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<payload>
<set>
<month>JAN,FEB,MAR</month>
<season>Season1</season>
<productId>ABCD</productId>
</set>
</payload>
The thing i am interested in is to split the comma seperated string into whole new set tags like:
<payload>
<set>
<month>JAN</month>
<season>Season1</season>
<productId>ABCD</productId>
</set>
</payload>
<payload>
<set>
<month>FEB</month>
<season>Season1</season>
<productId>ABCD</productId>
</set>
</payload>
<payload>
<set>
<month>MAR</month>
<season>Season1</season>
<productId>ABCD</productId>
</set>
</payload>
How would it be possible to do this with an XSLT?
回答1:
Using XSLT 1.0 you have to use a recursive call to a named template to split the string, here is a possible solution:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:param name="month"/>
<xsl:copy>
<xsl:apply-templates select="@* | node()">
<xsl:with-param name="month" select="$month"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="month">
<xsl:param name="month"/>
<month>
<xsl:choose>
<xsl:when test="$month">
<xsl:value-of select="$month"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates/>
</xsl:otherwise>
</xsl:choose>
</month>
</xsl:template>
<xsl:template name="splitMonths">
<xsl:param name="months"/>
<xsl:variable name="firstMonth" select="substring-before($months,',')"/>
<xsl:variable name="month">
<xsl:choose>
<xsl:when test="$firstMonth">
<xsl:value-of select="$firstMonth"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$months"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="otherMonths" select="substring-after($months,',')"/>
<xsl:if test="$month">
<payload>
<xsl:apply-templates>
<xsl:with-param name="month" select="$month"/>
</xsl:apply-templates>
</payload>
</xsl:if>
<xsl:if test="$otherMonths">
<xsl:call-template name="splitMonths">
<xsl:with-param name="months" select="$otherMonths"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template match="payload">
<xsl:call-template name="splitMonths">
<xsl:with-param name="months" select="set/month"/>
</xsl:call-template>
</xsl:template>
</xsl:stylesheet>
来源:https://stackoverflow.com/questions/9874261/xslt-split-comma-separated-file