我的XML包含这样的元素......
<root>
<data>
<data_item>
<colours>White, Red, Light Blue</colours>
</data_item>
</data>
</root>
我需要将其转换为......
<Items>
<item>
<custom_options>name=Options,type=multiple,required=0,price=0.0000,price_type=fixed,sku=,option_title=White|name=Options,type=multiple,required=0,price=0.0000,price_type=fixed,sku=,option_title=Red|name=Options,type=multiple,required=0,price=0.0000,price_type=fixed,sku=,option_title=Light Blue</custom_options>
</item>
</Items>
答案 0 :(得分:1)
根据分隔符创建递归模板以分割字符串:
<xsl:template name="splitter">
<xsl:param name="remaining-string"/>
<xsl:param name="pattern"/>
<xsl:choose>
<xsl:when test="contains($remaining-string,$pattern)">
<split-item>
<xsl:value-of select = "normalize-space(substring-before($remaining-string,$pattern))"/>
</split-item>
<xsl:call-template name="splitter">
<xsl:with-param name="remaining-string" select="substring-after($remaining-string,$pattern)"/>
<xsl:with-param name="pattern" select="$pattern"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<split-item>
<!-- normalize-space reduces a sequence of spaces to at most one space. Do your own stuff to format individual split item -->
<xsl:value-of select = "normalize-space($remaining-string)"/>
</split-item>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
在节点上调用此模板,该节点包含由模式分隔的项目序列:
<xsl:template match="/">
<xsl:variable name = "colors">
<xsl:for-each select="root/data/data_item">
<xsl:call-template name="splitter">
<xsl:with-param name="remaining-string" select="colours"/>
<xsl:with-param name="pattern" select="','"/>
</xsl:call-template>
</xsl:for-each>
</xsl:variable>
<!--Do your thing with the variable colors. I simply send it to the output stream. If you further want to iterate over the split items, make sure you convert the variable to a node-set-->
<xsl:copy-of select = "$colors"/>
</xsl:template>
在此处查看此行动:http://xsltransform.net/ei5Pwj6