【问题标题】:XSLT counting elements with a matching valueXSLT 计数具有匹配值的元素
【发布时间】:2020-10-09 12:23:28
【问题描述】:

我有一个关于this 问题的变体

给定以下输入 XML

<root>
  <zone name="zone1"/>
  <zone name="zone2"/>

  <device name="foo" zone="zone1"/>
  <device name="bar" zone="zone1"/>
</root>

我希望在 XSLT 中计算任何给定区域中有多少设备。

由于我的知识有限,我想出了:

...
<xsl:for-each select="zone">
  <tr>
    <td><xsl:value-of select="@name"/></td>
    <td><xsl:value-of select="count(/root/device[@zone = @name]"/></td>
  </tr>

如何在上面的语句中明确说明我想将&lt;device&gt; 元素中的zone 属性与当前&lt;zone&gt; 元素中的name 属性进行比较?

或者有没有更好/更清晰的方法来实现我的最终目标?

【问题讨论】:

  • 回答您的问题:您可以使用[@zone = current()/@name]。但是使用键更优雅也更高效。
  • 同意 100%。再次感谢。

标签: xml xslt


【解决方案1】:

最好使用 XSLT 的内置 key 机制来解决交叉引用:

XSLT 1.0

<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:key name="device-by-zone" match="device" use="@zone" />

<xsl:template match="root">
    <table>
        <xsl:for-each select="zone">
            <tr>
                <td>
                    <xsl:value-of select="@name"/>
                </td>
                <td>
                    <xsl:value-of select="count(key('device-by-zone', @name))"/>
                </td>
            </tr>
        </xsl:for-each> 
    </table>
</xsl:template>
    
</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 2011-07-03
    • 2020-09-28
    • 2021-12-28
    • 2023-01-09
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    相关资源
    最近更新 更多