【发布时间】:2018-06-29 17:19:20
【问题描述】:
如何将特定元素与相同类型的相邻兄弟元素合并为一个元素?我觉得这应该很简单,但找不到答案。
我的代码:
...
<nodeX>
<a>words</a>
<b>things</b>
<g>hi</g>
<g>there</g>
<g>friend</g>
<c>stuff</c>
<g>yep</g>
</nodeX>
...
期望的输出:
...
<nodeX>
<a>words</a>
<b>things</b>
<g>hi there friend</g>
<c>stuff</c>
<g>yep</g>
</nodeX>
...
我正在处理一个极其复杂且多变且层次结构很深的文档,因此除了这些元素会在某些上下文中出现以及当它们与相邻元素一起出现时,我无法处理许多假设。兄弟姐妹,那些兄弟姐妹需要合并。任何帮助将不胜感激。
更新:
使用 zx485 和 Martin Honnen 的建议,以下似乎可以很好地仅打开特定元素:
<xsl:template match="nodeX">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:for-each-group select="*" group-adjacent="name()">
<xsl:choose>
<xsl:when test="name()='g'">
<xsl:copy>
<xsl:copy-of select="current-group()/@*" />
<xsl:value-of select="current-group()"/>
</xsl:copy>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="current-group()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
【问题讨论】:
-
那么您究竟在哪里寻找答案呢?任何一本书都不应该用
group-adjacent来处理xsl:for-each-group吗?甚至规范在xsl:for-each-groupw3.org/TR/xslt20/#grouping-examples的示例列表中也有一个使用group-adjacent的示例 -
如果输入可以有其他相邻的元素,那么
<xsl:apply-templates select="."/>将无法处理它们,因为select="."将只选择每个组中的第一个项目,所以如果你选择<xsl:apply-templates select="current-group()"/>期待例如a或b或g也作为相邻的兄弟姐妹出现并希望全部处理。 -
好点,谢谢。已将更改添加到已发布的代码中以供后代使用。