xsl表示带数字的元素

时间:2016-08-02 16:50:59

标签: xml xslt xslt-1.0

我有xml如下:

<Result>
    <customer>
        <id>123abc</id>
        <lastName>John1</lastName>
        <firstName>Doe1</firstName>
        <phone>1234578900</phone>
    </customer>
    <customer>
        <id>456</id>
        <lastName>John2</lastName>
        <firstName>Doe2</firstName>
        <phone>1234587900</phone>
    </customer>
    <customer>
        <id>789</id>
        <lastName>John3</lastName>
        <firstName>Doe3</firstName>
        <phone>1234467900</phone>
    </customer> 
    <customer>
        <id>012</id>
        <lastName>John4</lastName>
        <firstName>Doe4</firstName>
        <phone>1236567900</phone>
    </customer>
    <customer>
        <id>012jkl</id>
        <lastName>John5</lastName>
        <firstName>Doe5</firstName>
        <phone>1236567900</phone>
    </customer> 
    <customer>
        <id>235</id>
        <lastName>John6</lastName>
        <firstName>Doe6</firstName>
        <phone>1232567900</phone>
    </customer>
    <customer>
        <id>568</id>
        <lastName>John7</lastName>
        <firstName>Doe7</firstName>
        <phone>1237567900</phone>
    </customer
</Result>

我只需要输出5个客户结果,其中id是数字。如果请求少于5个客户,那么我需要输出所有。但如果请求超过5,我只需要输出5个结果,其中id是数字。如何使用样式表

实现这一目标

预期产出:

<Result>
    <customer>
        <id>456</id>
        <lastName>John2</lastName>
    </customer>
    <customer>
        <id>789</id>
        <lastName>John3</lastName>
    </customer>
    <customer>
        <id>012</id>
        <lastName>John4</lastName>
    </customer>
    <customer>
        <id>235</id>
        <lastName>John6</lastName>
    </customer>
    <customer>
        <id>568</id>
        <lastName>John7</lastName>
    </customer> 
</Result>

我的xsl:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/Result">
    <xsl:copy>
        <xsl:for-each select="customer[position() &lt;= 5]">
            <xsl:copy>
                <xsl:if test="number(id/text())">
                    <xsl:copy-of select="id | lastName"/>
                </xsl:if>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>    
</xsl:stylesheet>

这只返回前3个元素。我需要做出哪些调整才能获得客户ID为数字的5个ID

1 个答案:

答案 0 :(得分:1)

要返回第一个(按文档顺序)5个<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/Result"> <xsl:copy> <xsl:for-each select="customer[not(translate(id, '0123456789', ''))][position() &lt;= 5]"> <xsl:copy> <xsl:copy-of select="id | lastName"/> </xsl:copy> </xsl:for-each> </xsl:copy> </xsl:template> </xsl:stylesheet> 仅包含数字的客户:

XSLT 1.0

var x = document.getElementById('input1').value;
var y = document.getElementById('input2').value;
if (x.length > 0 && y.length > 0) {
    //execute code
}