xml - 如何在 XSLT 2.0 中删除字符串周围的逗号和“[]”
问题描述
我正在尝试在元素中重新创建一组值作为单独的节点集。
XML 示例:
<VALUES>
<VALUE>[example],[example1],[good,example],[test]</VALUE>
<VALUES>
XSLT:
<xsl:template name="SimpleStringLoop">
<xsl:param name="input"/>
<xsl:if test="string-length($input) > 0">
<xsl:variable name="v" select="substring-before($input, ',')"/>
<xsl:value-of select="$v"/>
<xsl:call-template name="SimpleStringLoop">
<xsl:with-param name="input" select="substring-after($input, ',')"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template match="VALUE">
<xsl:call-template name="SimpleStringLoop">
<xsl:with-param name="input" select="."/>
</xsl:call-template>
<xsl:value-of select="substring-before(substring-after(.,'['),']')"/>
</xsl:template>
预期输出:
<VALUES>
<VALUE>example</VALUE>
<VALUE>example1</VALUE>
<VALUE>good,example</VALUE>
<VALUE>test</VALUE>
<VALUES>
我能够用逗号分隔。我也认为通过计算逗号并创建相同数量的元素并编写它们来为每个值设置是有意义的。如何摆脱字符串周围的“[]”?
解决方案
我会使用analyze-string
,在 XSLT 3 中,您可以将其作为 XPath 函数调用,并简单地处理fn:match
函数返回的 XML 元素:
<xsl:template match="VALUE">
<xsl:apply-templates select="analyze-string(., '\[([^\[]+)\]')//fn:match"/>
</xsl:template>
完整的例子
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
expand-text="yes"
exclude-result-prefixes="#all"
version="3.0">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:output indent="yes"/>
<xsl:template match="VALUE">
<xsl:apply-templates select="analyze-string(., '\[([^\[]+)\]')//fn:match"/>
</xsl:template>
<xsl:template match="fn:match">
<VALUE>{fn:group[@nr = 1]}</VALUE>
</xsl:template>
</xsl:stylesheet>
在 XSLT 2 中,您可以xsl:analyze-string
改为使用,然后使用xsl:matching-substring
inside 来输出VALUE
元素:
<xsl:template match="VALUE">
<xsl:analyze-string select="." regex="\[([^\[]+)\]">
<xsl:matching-substring>
<VALUE>
<xsl:value-of select="regex-group(1)"/>
</VALUE>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:template>