xsl模板匹配

时间:2012-07-05 19:13:44

标签: xml xslt

我正在使用xsl和xml创建xml

以下是XML

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

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

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

但我很困惑如何带来如下的值

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

任何人都可以帮助我如何实现上述价值

由于 米

1 个答案:

答案 0 :(得分:0)

在这种情况下最简单的方法是拆分空间分隔符。如果你被限制在XSLT 1.0中,最简单的方法是通过EXSLT库(默认情况下在许多XSLT实现中都可用,例如PHP)。

您可以在this 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>

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

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

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

您可以在this (separate) 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>
相关问题