【问题标题】:how to add condition in xslt?如何在 xslt 中添加条件?
【发布时间】:2017-11-01 22:35:52
【问题描述】:

我试图解析的是xml

<a>
    <b Number="first">
        <c Over="1">
            <name>1</name>
        </c>
        <c Over="2">
            <name>2</name>
        </c>
    </b>
    <b Number="Second">
        <c Over="1">
            <name>3</name>
        </c>
        <c Over="2">
            <name>4</name>
        </c>
    </b>
</a>

使用分组概念

我喜欢这个

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext">
    <xsl:key name="node-by-over" match="c" use="@Over" />

    <xsl:template match="a">

        <xsl:apply-templates select="b[@Number='first']/c[generate-id() = generate-id(key('node-by-over', @Over)[1])]"/>

    </xsl:template>

    <xsl:template match="c">
        <table id="">

            <xsl:for-each select="key('node-by-over', @Over)">
                <tr>
                    <td>balls:::<xsl:value-of select="name"/></td>

                </tr>
            </xsl:for-each>
        </table>
    </xsl:template>

</xsl:stylesheet>

我的输出

<table><tr><td>balls:::1</td></tr><tr><td>balls:::3</td></tr></table><table><tr><td>balls:::2</td></tr><tr><td>balls:::4</td></tr></table>

预期

<table><tr><td>balls:::1</td></tr><tr><td>balls:::2</td></tr></table>

为什么它会给出这样的输出 1,3,2,4 ???我已经在applytemplate中使用了提及我需要所有c 节点,其中@Number 是first

<xsl:apply-templates select="b[@Number='first']/c[generate-id() = generate-id(key('node-by-over', @Over)[1])]"/>

预期输出 1,2(名称解析)

【问题讨论】:

  • 不清楚您要做什么。我怀疑您对密钥的使用过于复杂——您提到您“需要@Number 为first 的所有c 节点”,这可以在不使用任何密钥的情况下更干净地完成一点也不。对于您的预期输出,您真的只需要包含在最上面的b 元素中的两个name 值吗?
  • 嗨我能解决我的问题

标签: xml xslt xslt-1.0 xslt-grouping


【解决方案1】:

您的预期输出表明您想要:

  • 每个组中仅包含第一个 c/name 元素的列表 (按Over 属性分组),
  • 单个 &lt;table&gt; 元素中。

(您应该在帖子中写过以上内容)。

因此,对脚本的基本更改归结为以下几点:

  • &lt;table&gt; 移动到match="a" 模板。
  • match="c"模板中删除&lt;xsl:for-each(生成输出 只是当前组中的第一个元素)。

这是完整的脚本:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" omit-xml-declaration="yes"/>
  <xsl:key name="node-by-over" match="c" use="@Over" />

  <xsl:template match="a">
    <table>
      <xsl:apply-templates select=
        "b[@Number='first']/c[generate-id() =
        generate-id(key('node-by-over', @Over)[1])]"/>
    </table>
  </xsl:template>

  <xsl:template match="c">
    <tr><td>balls:::<xsl:value-of select="name"/></td></tr>
  </xsl:template>
</xsl:stylesheet>

编辑

实际上select 中的[@Number='first'] 是不需要的,因为分组只从每个组中选择第一个c/name 元素(从整个文档中收集)。

或者如果某些其他机制已经将元素分组(到 first第二个组,可能更多),然后是基于key的整个分组 不需要。 也许只是select="b[@Number='first']" 就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2011-03-01
    • 1970-01-01
    • 2010-09-24
    • 2019-04-04
    相关资源
    最近更新 更多