来源:
<Data>
<value>M1,M2,M3,M4,M5,M6</value>
</Data>
需要将它们显示为
输出:
<ABCD>
<value1>M1</value1>
<value2>M2</value2>
<value3>M3</value3>
<value4>M4</value4>
<value5>M5</value5>
<value6>M6</value6>
</ABCD>
XSLT:
我实际上想根据“,”拆分值并将它们放置在不同的变量中。 使用str-split(),我可以将它加载到不同的变量中吗?
最佳答案
此 XSLT 1.0 转换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
<ABCD>
<xsl:apply-templates/>
</ABCD>
</xsl:template>
<xsl:template match="value/text()" name="split">
<xsl:param name="pText" select="."/>
<xsl:param name="pOrd" select="1"/>
<xsl:if test="$pText">
<xsl:element name="value{$pOrd}">
<xsl:value-of select=
"substring-before(concat($pText, ','), ',')"/>
</xsl:element>
<xsl:call-template name="split">
<xsl:with-param name="pText" select="substring-after($pText, ',')"/>
<xsl:with-param name="pOrd" select="$pOrd+1"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
应用于提供的 XML 文档时:
<Data>
<value>M1,M2,M3,M4,M5,M6</value>
</Data>
产生想要的正确结果:
<ABCD>
<value1>M1</value1>
<value2>M2</value2>
<value3>M3</value3>
<value4>M4</value4>
<value5>M5</value5>
<value6>M6</value6>
</ABCD>
说明:
递归命名模板,当传递的文本参数变为空字符串时具有停止条件。
正确使用
xsl:element
和 AVT 。正确使用标准 XPath 函数
substring-before()
和substring-after
正确使用 sentinel 简化代码并提高效率。
关于xslt - 使用 xslt 拆分标签的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11207626/