0

我不是 XSL 专家,我在为简单的逻辑苦苦挣扎:

我有一个值为“A、B、C”的 XSL 变量,想要将其拆分并将各个值存储到三个不同的 XSL 变量中,例如

X= A
Y= B
Z= C

但有时它可能只有一个/两个值或没有值......

如果它只有一个值,那么变量值应该是

X= A
Y=
Z=

如果它没有任何价值,那么

X=
Y=
Z=

请帮助我使用相同的 XSL 代码

让我们说:

Tags 的值为“Test,Demo,Sample”,那么我想像这样拆分

<xsl:choose>
    <xsl:when test="contains($Tags,',')">
        <xsl:variable name="Tags1">
            <xsl:value-of select="substring-before($Tags,',')" />
        </xsl:variable>
        <xsl:variable name="ATag1">
            <xsl:value-of select="substring-after($Tags,',')" />
        </xsl:variable>
    </xsl:when>
    <xsl:otherwise>
        <xsl:variable name="Tags1"/>
        <xsl:variable name="ATags1"/>
    </xsl:otherwise>
</xsl:choose>

<xsl:choose>
    <xsl:when test="contains($ATags1,',')">
        <xsl:variable name="Tags2">
            <xsl:value-of select="substring-before($ATags1,',')" />
        </xsl:variable>
        <xsl:variable name="ATag2">
            <xsl:value-of select="substring-after($ATags1,',')" />
        </xsl:variable>
    </xsl:when>
    <xsl:otherwise>
        <xsl:variable name="Tags2"/>
        <xsl:variable name="ATags2"/>
    </xsl:otherwise>
</xsl:choose>



<xsl:choose>
    <xsl:when test="contains($ATags2,',')">
        <xsl:variable name="Tags3">
            <xsl:value-of select="substring-before($ATags2,',')" />
        </xsl:variable>
    </xsl:when>
    <xsl:otherwise>
        <xsl:variable name="Tags3"/>
    </xsl:otherwise>
</xsl:choose>

但是它对我不起作用...

4

1 回答 1

2

这是一个 XSLT 2.0 解决方案

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()">
  <xsl:variable name="vSeq" select="tokenize(.,',')"/>

  <xsl:variable name="X" select="$vSeq[1]"/>
  <xsl:variable name="Y" select="$vSeq[2]"/>
  <xsl:variable name="Z" select="$vSeq[3]"/>

  <xsl:value-of select=
   "concat('X = ',$X, '&#xA;',
           'Y = ',$Y, '&#xA;',
           'Z = ',$Z, '&#xA;'
           )"
   />
 </xsl:template>
</xsl:stylesheet>

当此转换应用于以下 XML 文档时

<t>A,B,C</t>

产生了想要的正确结果

X = A
Y = B
Z = C

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:template match="text()">
  <xsl:variable name="X" select="substring-before(.,',')"/>
  <xsl:variable name="Y" select=
   "substring-before(substring-after(.,','),',')"/>
  <xsl:variable name="Z" select=
   "substring-before(substring-after(.,','),',')"/>

  <xsl:value-of select=
   "concat('X = ',$X, '&#xA;',
           'Y = ',$Y, '&#xA;',
           'Z = ',$Z, '&#xA;'
           )"
   />
 </xsl:template>
</xsl:stylesheet>

当此转换应用于同一个 XML 文档(如上)时,会产生所需的正确结果

X = A
Y = B
Z = B
于 2010-12-23T20:22:07.797 回答