【问题标题】:How to group elements based on their siblings using XSLT如何使用 XSLT 根据同级元素对元素进行分组
【发布时间】:2016-07-04 19:48:25
【问题描述】:

我正在尝试根据周围同级元素的开始和结束属性对几个元素进行分组。

示例 XML:

<list>
  <item>One</item>
  <item class="start">Two</item>
  <item>Three</item>
  <item class="end">Four</item>
  <item>Five</item>
  <item class="start">Six</item>
  <item class="end">Seven</item>
  <item>Eight</item>
</list>

期望的结果:

<body>
  <p>One</p>
  <div>
    <p>Two</p>
    <p>Three</p>
    <p>Four</p>
  </div>
  <p>Five</p>
  <div>
    <p>Six</p>
    <p>Seven</p>
  </div>
  <p>Eight</p>
</body>

我使用以下 XSLT 接近了预期的结果。但是,following-sibling 匹配在到达结束属性后不会停止。此外,标准匹配会重复已从后续兄弟匹配中输出的元素。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
    <xsl:strip-space elements="*" />
    <xsl:template match="/">
        <xsl:apply-templates />
    </xsl:template>
    <xsl:template match="list">
        <body>
            <xsl:apply-templates />
        </body>
    </xsl:template>
    <xsl:template match="item">
        <p>
            <xsl:apply-templates />
        </p>
    </xsl:template>
    <xsl:template match="item[@class='start']">
        <div>
            <p><xsl:apply-templates /></p>
            <xsl:apply-templates select="following-sibling::*[not(preceding-sibling::*[1][@class='end'])]" />
        </div>
    </xsl:template>
</xsl:transform>

【问题讨论】:

标签: xslt xslt-2.0


【解决方案1】:

既然您使用的是 XSLT 2.0,何不好好利用它:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/list">
    <body>
        <xsl:for-each-group select="item" group-starting-with="item[@class='start']">
            <xsl:for-each-group select="current-group()" group-ending-with="item[@class='end']">
                <xsl:choose>
                    <xsl:when test="count(current-group()) gt 1">
                        <div>
                            <xsl:apply-templates select="current-group()" />
                        </div>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:apply-templates select="current-group()" />
                    </xsl:otherwise>
                </xsl:choose>
            </xsl:for-each-group>
        </xsl:for-each-group>
    </body>
</xsl:template>

<xsl:template match="item">
    <p>
        <xsl:value-of select="."/>
    </p>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 如果此列表包含数百个元素和子元素,是否会出现性能问题?
  • 数百?可能不是。但是您需要使用您将在生产中使用的实际处理器自己测试类似的东西。
  • 会不会碰巧有另一种方法由item[@class='start'] 匹配触发?
  • 恕我直言,在 XSLT 2.0 中进行分组的最佳方式是使用为此目的明确提供的方法。
  • 非常感谢。上面的语法很容易理解。我将不得不关注性能,因为我的整个输入将是这个项目列表,并且开始/结束分组实际上并不经常发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多