如何基于EOP标签截断table内数据并实现分页处理?
解决XML按EOP分页时仅保留表格内EOP之前数据的问题
你当前需要将包含<eop/>标签的XML内容分割为独立DIV分页,但当<eop/>出现在<table>内部时,现有逻辑会错误保留EOP之后的表格行数据。以下是调整后的XSLT解决方案,确保只保留每个表格中第一个<eop/>之前的内容,同时维持正确的分页结构。
修改后的XSLT代码
<?xml version="1.0" encoding="utf-8" ?> <xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" indent="yes" encoding="UTF-8"/> <xsl:template match="/"> <xsl:variable name="preprocessed"> <xsl:apply-templates mode="preprocess"/> </xsl:variable> <html> <head> <style> body { direction: rtl; } div.page { margin: 1cm; padding: 1cm; border: 1px solid #000; height: 27.7cm; width: 19cm; background-color: rgb(204, 204, 204); page-break-after: always; } div.page:last-child { page-break-after: avoid; } thead { display: table-header-group; } </style> </head> <body> <xsl:apply-templates select="$preprocessed/node()"/> </body> </html> </xsl:template> <!-- 通用节点复制模板 --> <xsl:template match="node()" mode="preprocess"> <xsl:copy> <xsl:apply-templates select="node()" mode="preprocess"/> </xsl:copy> </xsl:template> <!-- 按EOP分割paragraph,过滤空段落 --> <xsl:template match="paragraph" mode="preprocess"> <xsl:for-each-group select="node()" group-adjacent="boolean(self::eop)"> <xsl:if test="not(current-group()[self::eop])"> <paragraph> <xsl:copy-of select="current-group()"/> </paragraph> </xsl:if> </xsl:for-each-group> </xsl:template> <!-- 处理表格:仅保留tbody中第一个EOP之前的内容 --> <xsl:template match="table" mode="preprocess"> <table> <xsl:copy-of select="thead"/> <tbody> <xsl:copy-of select="tbody/node()[not(following-sibling::eop) and not(preceding-sibling::eop)] | tbody/node()[preceding-sibling::eop][1]/preceding-sibling::node()"/> </tbody> </table> </xsl:template> <!-- 生成分页DIV --> <xsl:template match="mainBody"> <xsl:for-each select="paragraph"> <div class="page"> <xsl:apply-templates select="*"/> </div> </xsl:for-each> </xsl:template> <!-- 基础标签转换模板 --> <xsl:template match="heading"> <h1> <xsl:value-of select="."/> </h1> </xsl:template> <xsl:template match="p"> <p> <xsl:value-of select="."/> </p> </xsl:template> <xsl:template match="table"> <table> <xsl:apply-templates/> </table> </xsl:template> <xsl:template match="thead"> <thead> <xsl:apply-templates/> </thead> </xsl:template> <xsl:template match="tbody"> <tbody> <xsl:apply-templates/> </tbody> </xsl:template> <xsl:template match="tr"> <tr> <xsl:apply-templates/> </tr> </xsl:template> <xsl:template match="th"> <th> <xsl:apply-templates/> </th> </xsl:template> <xsl:template match="td"> <td> <xsl:apply-templates/> </td> </xsl:template> </xsl:stylesheet>
关键修改说明
- 表格内容过滤逻辑:在
preprocess模式的<table>模板中,通过节点选择器精准保留<tbody>里第一个<eop/>之前的所有行,同时兼容没有EOP标签的完整表格。 - 段落分割优化:在
<paragraph>预处理模板中加入判断,避免EOP连续出现时生成空的分页段落。 - 移除错误分组逻辑:删除原代码中针对表格的错误分组逻辑,替换为正常的节点遍历,确保只输出预处理后保留的表格内容。
内容的提问来源于stack exchange,提问作者גבי עובד
相关产品推荐
相关产品推荐

