如何获取具有相同名称的所有元素值

问题描述 投票:0回答:1

我有一个要求,我需要获取名为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等等。

xml xslt xpath
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.