0

我正在使用带有 xml 的 xsl 创建 xml

这是 XML 的代码

<?xml version="1.0" encoding="utf-8"?>
<example>
<sample>245 34</sample>
<sample1>24 36</sample1>
</example>

在 XSL 的帮助下,我想拆分 xml 值

当我在谷歌检查时,我看到有一种方法可以使用 substring-before 或 substring-after(query)

但我有点困惑如何带来如下值

<example>
<text>245</text>
<text>34</text
<text>24</text>
<text>36</text>
</example>

任何人都可以帮助我如何带来上述价值

谢谢米

4

1 回答 1

0

在这种情况下,最简单的方法是在空格分隔符上进行拆分。如果您受限于 XSLT 1.0,最简单的方法是通过 EXSLT 库(默认情况下,在许多 XSLT 实现中可用,例如 PHP)。

您可以在此 XMLPlayground上运行以下命令(请参阅输出)。

<!-- root -->
<xsl:template match='/'>
    <example>
        <xsl:apply-templates select='*' />
    </example>
</xsl:template>

<!-- match sample nodes -->
<xsl:template match="example/*">
    <xsl:apply-templates select='str:split(., " ")' />
</xsl:template>

<!-- match token nodes (from EXSLT split()) -->
<xsl:template match='token'>
    <text><xsl:value-of select='.' /></text>
</xsl:template>

如 Playground 所示,要使用 EXSLT(前提是您可以使用它),您需要在开始xsl:stylesheet标记中声明其命名空间。例如,要使用它的字符串库(就像我们在这里使用的那样split()),你可以输入:

xmlns:str="http://exslt.org/strings"
extension-element-prefixes="str"

[编辑] - 如果您坚持使用子字符串方法,这是可能的,但更冗长,因为没有生成节点集的能力(这是 EXSLTsplit()所做的),因此,在该节点集上应用模板,唯一的你包里的技巧是递归——一个模板调用自己的次数与其中的空间特征一样多。

您可以在这个(单独的)XMLPlayground上运行它

<!-- root child nodes -->
<xsl:template match='example/*'>
    <xsl:call-template name='output'>
        <xsl:with-param name='source' select='.' />
    </xsl:call-template>
</xsl:template>


<!-- output - expects two params: -->
<!-- @output_str - the sub-string to output to a <text> node this time (has value only on self-call, i.e. recursion -->
<!-- @source - the source string on which to recurse, for more spaces in the string -->

<xsl:template name='output'>

    <xsl:param name='output_str' />
    <xsl:param name='source' />

    <!-- output something this time? -->
    <xsl:if test='$output_str'>
        <text><xsl:value-of select='$output_str' /></text>
    </xsl:if>

    <!-- recurse... -->
    <xsl:if test='$source'>
        <xsl:choose>

            <!-- $source contains spaces - act on the string before the next space -->
            <xsl:when test='contains($source, " ")'>
                <xsl:call-template name='output'>
                    <xsl:with-param name='output_str' select='substring-before($source, " ")' />
                    <xsl:with-param name='source' select='substring-after($source, " ")' />
                </xsl:call-template>
            </xsl:when>

            <!-- source doesn't contain spaces - act on it in its entirety -->
            <xsl:otherwise>
                <xsl:call-template name='output'>
                    <xsl:with-param name='output_str' select='$source' />
                </xsl:call-template>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:if>
</xsl:template>
于 2012-07-05T20:37:16.153 回答