【发布时间】: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 2.0 时,您可以尝试使用 xsl:for-each-group group-starting-with/group-ending-with,请参阅 w3.org/TR/xslt20/#grouping-examples。