【问题标题】:How to get all the element value which have the same name如何获取所有具有相同名称的元素值
【发布时间】:2018-01-18 21:05:00
【问题描述】:

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

【问题讨论】:

  • 您可以使用 XSLT 2.0 吗?您可以在单个 xpath 表达式中执行此操作,而无需对索引进行硬编码。
  • 我可以试一试。
  • 如果您可以使用 XSLT 2.0,您可以使用字符串连接功能...string-join(//Account/IDs/ID, '$')
  • 大赞@Tim C
  • 如何在同一个 XPATH 中再添加一个条件,如果没有 ID,它还会打印“EMPTY”

标签: xml xslt xpath


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多