【问题标题】:On splitting XHTML into chapters with XSLT关于使用 XSLT 将 XHTML 拆分为章节
【发布时间】:2016-09-25 18:46:17
【问题描述】:

我有以下 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>

【问题讨论】:

  • 考虑显示输入样本和相应输出样本的最小但完整的 sn-ps,以便我们了解您想要实现的目标。
  • @MartinHonnen 添加了一个示例
  • 看来我需要先找到所有h1(或h2)标签中最深的共同祖先。但是那该怎么办呢?
  • 我还没有想出如何找到最深的共同祖先
  • 在问题的例子中,最深的共同祖先是&lt;div class="container"&gt;

标签: xml xslt xhtml xslt-2.0


【解决方案1】:

我已经解决了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

【讨论】:

  • 虽然这在理论上可以回答问题,it would be preferable 在这里包含答案的基本部分,并提供链接以供参考。
【解决方案2】:

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

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

有帮助吗?

【讨论】:

    【解决方案3】:

    如果你使用

    <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>
    

    那么对于您的示例,我认为任务已解决。这完全取决于您输入的规律性。

    【讨论】:

    • class="container" 只是一个例子。没有理由假设该类将是 container,也没有理由认为只有一层封闭的 div。请删除您的答案,这是错误的。
    • 如果您从像 Martin 这样的人那里得到错误答案,它应该告诉您您的问题有问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    • 2013-11-09
    相关资源
    最近更新 更多