如何获取具有相同名称

时间:2018-01-18 11:36:47

标签: xml xslt xpath

我有一个要求,我需要获取名为ID的元素的所有值,连接它们并显示。我现在有了解决方案。难道没有更好的方法来获得价值观吗?

输入:

<Response>
    <Error/>
    <Data>
        <Account>
            <IDs>
                <ID>386</ID>
                <ID>287</ID>
                <ID>997</ID>
                <ID>2709</ID>
            </IDs>
        </Account>
    </Data>
</Response>

硬编码XSL:

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:template match="/*">
            <xsl:copy-of select="concat(//Account/IDs/ID[1]/text(),'$',//Account/IDs/ID[2]/text(),'$',//Account/IDs/ID[3]/text(),'$',//Account/IDs/ID[4]/text() )"/>
    </xsl:template>
</xsl:stylesheet>

输出:

386$287$997$2709

动态XSL:

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/> 
    <xsl:template match="ID">
        <xsl:value-of select="concat(., '$')"/>
    </xsl:template>        
    <xsl:template match="text()"/>
</xsl:stylesheet>

它提供与上面相同的输出:

386$287$997$2709$

所以两者都适合我。但是我想的是,有没有办法可以在硬编码的XSL 中动态设置XPATH,这样它就可以获取ID的所有值,而不是提及1,2,3 ,4等等。

1 个答案:

答案 0 :(得分:0)

在XSLT 2和3中,你可以直接使用纯XPath,正如Tim已经指出使用函数string-joinstring-join(//Account/IDs/ID, '$'),但你也可以依赖xsl:value-of<xsl:value-of select="//Account/IDs/ID" separator="$"/>

相关问题