【问题标题】:XSLT - get number value of the text() nodeXSLT - 获取 text() 节点的数值
【发布时间】:2016-04-30 22:06:12
【问题描述】:

我有如下的 XML 文件,

<sec>
    <para>Section 1- TOC</para>
    <para>Section 4* Main</para>
    <para>Section 3$ Basic content</para>
    <para>Section 11_ Section 10</para>
    <para>Section 15@ Appendix 6</para>
</sec>

我需要使用函数在text() 节点中获取数字后跟“Section”字符串。

示例:

<xsl:function name="abc:get-section-number">
        <xsl:param name="string" as="xs:string"/>

        <xsl:sequence select="tokenize($string,'\d+')[1]"/>
    </xsl:function>

这个例子返回数字之前的子字符串,但是我需要在'Section'字符串之后获取数字值..(输出值应该是1,4,3,11和15)

我尝试了一些内置函数(string-before、strong-after、matches..),但找不到任何合适的解决方案。

谁能给我一个方法来获得这个数值?

【问题讨论】:

  • 检查this answer。你似乎只需要Section\s+(\d+)。然后&lt;xsl:value-of select="regex-group(1)"/&gt;

标签: regex xslt xslt-2.0


【解决方案1】:

您可以使用analyze-string,正如评论中已经建议的那样,请参阅http://xsltransform.net/3NJ38Zy 以获取工作示例

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:abc="http://example.com/abc"
    exclude-result-prefixes="xs abc">

    <xsl:function name="abc:get-section-number" as="xs:integer">
        <xsl:param name="string" as="xs:string"/>
        <xsl:analyze-string select="$string" regex="^Section\s+([0-9]+)">
            <xsl:matching-substring>
                <xsl:sequence select="xs:integer(regex-group(1))"/>
            </xsl:matching-substring>
        </xsl:analyze-string>
    </xsl:function>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="para">
        <xsl:copy>
            <xsl:value-of select="abc:get-section-number(.)"/>
        </xsl:copy>
    </xsl:template>
</xsl:transform>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 2012-01-20
    • 2018-12-21
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多