用XSLT将XHTML分成章节

时间:2016-05-27 12:13:03

标签: xml xslt xhtml xslt-2.0

我有以下XSLT 2.0代码将XHTML文件拆分为章节:

<xsl:for-each-group
  select=".//html:*[local-name() eq $chapter-tag][1]/(.|following-sibling::*)"
  group-starting-with="html:*[local-name() eq $chapter-tag]">
  ...
</xsl:for-each-group>

(此处$chapter-tagh1h2)。

但是此代码不适用于以下XHTML片段:

<div class="header">
  <h1>Header</h1>
</div>
<p>...</p>
...

当标题“隐藏”在其他标记内时,请帮助做正确的事情。

完整示例:

<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Test</title>
  </head>
  <body>
    <div class="container">
      <div class="header">
        <h1>First chapter</h1>
      </div>
      <p>First chapter text.</p>
      <p>Blah, blah, blah...</p>
      <div class="header">
        <h1>Second chapter</h1>
      </div>
      <p>Second chapter text.</p>
      <p>Blah, blah, blah...</p>
    </div>
  </body>
</html>

这应创建以下元素组(“章节”):

      <div class="header">
        <h1>First chapter</h1>
      </div>
      <p>First chapter text.</p>
      <p>Blah, blah, blah...</p>

      <div class="header">
        <h1>Second chapter</h1>
      </div>
      <p>Second chapter text.</p>
      <p>Blah, blah, blah...</p>

3 个答案:

答案 0 :(得分:0)

如果您使用

<xsl:template match="div[@class = 'container']">
  <xsl:for-each-group select="*" group-starting-with="div[@class = 'header' and h1]">
     <xsl:copy-of select="current-group()"/>
  </xsl:for-each-group>
</xsl:template>

然后对于您的样本我认为任务已经解决。这一切都取决于你的输入是多么规律。

答案 1 :(得分:0)

仍然不确定完全您的要求是什么,但是模式

group-starting-with="*[descendant-or-self::h1]"

有帮助吗?

答案 2 :(得分:0)

我在my real code解决了这个问题。现在它有效。查阅我的代码。

<xsl:template name="split">
  <xsl:variable name="container" select="my:lca(.//html:*[local-name() eq $chapter-tag])"/>
  <xsl:variable name="start" select="$container/node()[descendant-or-self::html:*[local-name() eq $chapter-tag]][1]"/> <!-- the first chapter header in the document -->
  <xsl:for-each-group select="$start|$start/following-sibling::node()"
                      group-starting-with="*[descendant-or-self::html:*[local-name() eq $chapter-tag]]">
    <!-- ... -->
  </xsl:for-each-group>
</xsl:template>

my:lca用户定义的函数在Finding the lowest common ancestor of an XML node-set

中定义
相关问题