使用正则表达式从xml元素中获取数字

时间:2017-12-04 11:38:14

标签: xml xslt xslt-1.0

我的元素有两个数字,用[ - ]分隔,例如120-125。 现在使用xslt我想得到这两个数字并用这些值创建xml元素,最后我想要这样的东西:

<first>120</first>
<second>125</second>

我怎样才能做到这一点?

修改

我要更改的xml结构如下所示:

<issue>
    <number>3</number>
    <year>2017</year>
    <article>
        <title>Title</title>
        <author>
            <firstname>name</firstname>
        </author>
        <pages>71-72</pages>
        <reference>reference</reference>
    </article>
</issue>

XSLT:

<issue>
    <number>
        <xsl:value-of select="number"/>
    </number>
    <year>
        <xsl:value-of select="year"/>
    </year>
    <xsl:for-each select="article">
        <article>
            <title>
                <xsl:value-of select="title"/>
            </title>
            <author>
                <firstname>
                    <xsl:value-of select="firstname"/>
                </firstname>
            </author>
            <xsl:template match="pages">
                <xsl:copy>
                    <first>
                        <xsl:value-of select="substring-before(., '-')" />
                    </first>
                    <second>
                        <xsl:value-of select="substring-after(., '-')" />
                    </second>
                </xsl:copy>
            </xsl:template>
            <reference>
                <xsl:value-of select="reference"/>
            </reference>
        </article>
    </issue>

输出我想要的XML:

<issue>
    <number>3</number>
    <year>2017</year>
    <article>
        <title>Title</title>
        <author>
            <firstname>name</firstname>
        </author>
        <first>71</first>
        <second>71</second>
        <reference>reference</reference>
    </article>
</issue>

1 个答案:

答案 0 :(得分:2)

<xsl:template match="pages"><xsl:for-each>。考虑到您共享的XSL,您需要修改它,如下所示。我刚刚修改了用于分割<pages>值的代码。其余代码保持不变。

<xsl:for-each select="article">
    <article>
        ...
        <first><xsl:value-of select="substring-before(pages, '-')" /></first>
        <second><xsl:value-of select="substring-after(pages, '-')" /></second>
        ...
    </article>
</xsl:for-each>