选择除两个节点之外的所有兄弟节点

时间:2015-02-10 21:08:40

标签: xml xslt xpath

我必须选择h1节点之间的所有内容。

<html>
<h1>Index</h1>
<p>some content</p>
<p>some more content</p>
<h1>Index 2</h1>
<p>some content</p>
<h2>other content</h2>
<h1>Index 3</h1>
<p>some  content</p>
<p>other content</p>
<h1>Index 4</h1>
<h2>some content</h2>
<p>other content</p>
</html>

哪个应该是这样的:

<heading>
  <p>some content</p>
  <p>some more content</p>
<heading>
...

2 个答案:

答案 0 :(得分:3)

在XSLT 2.0中,这是group-starting-with的一个很好的案例:

<xsl:template match="html">
  <root>
    <xsl:for-each-group select="*" group-starting-with="h1">
      <heading text="{.}">
        <xsl:sequence select="current-group() except ."/>
      </heading>
    </xsl:for-each-group>
  </root>
</xsl:template>

current-group()是从一个h1(包括)到下一个(不包括)的整个元素组,.是文档顺序(h1)中组中的第一个节点,因此{ {1}}为您提供所需的节点。

如果h1元素之间可能存在不包含在其他元素中的文本,则可能更喜欢使用current-group() except .而不是select="node()",例如

select="*"

答案 1 :(得分:1)

这就是诀窍。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

    <xsl:template match="/html">
      <xsl:apply-templates select="h1" />
    </xsl:template>

    <xsl:template match="h1">
      <heading>
        <xsl:copy-of select="following-sibling::*[preceding-sibling::h1[1] = current()][not(self::h1)]"/>
      </heading>
    </xsl:template>

</xsl:stylesheet>