You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用XSLT 2.0 result-document替代redirect:write生成多HTML导航失败

解决XSLT 1.0 redirect:write转XSLT 2.0 result-document后的多HTML输出问题

核心问题排查

你遇到的问题本质是result-document的使用逻辑或配置和原redirect:write不匹配,导致多文件输出未触发,同时链接路径失效。以下是针对性的修复步骤:

1. 修正result-document的基础用法

原Xalan的redirect:write是扩展元素,而xsl:result-document是XSLT 2.0标准元素,需调整语法确保每个独立输出都被正确触发:

  • 移除原redirect命名空间声明(如xmlns:redirect="http://xml.apache.org/xalan/redirect")
  • 将每个redirect:write替换为xsl:result-document,明确指定href属性(对应原file属性),并添加method="html"保证输出格式一致:
    <!-- 原Xalan代码 -->
    <redirect:write file="page1.html">
      <html><!-- 页面1内容 --></html>
    </redirect:write>
    
    <!-- 替换为Saxon兼容代码 -->
    <xsl:result-document href="page1.html" method="html">
      <html><!-- 页面1内容 --></html>
    </xsl:result-document>
    
  • 若使用变量动态生成文件名,确保变量插值正确,比如:
    <xsl:result-document href="{$page-id}.html" method="html">
      <!-- 动态页面内容 -->
    </xsl:result-document>
    

2. 调整Java调用Saxon的配置

原Xalan的TransformerFactory替换为Saxon实现后,需确保配置允许多文件输出:

  • 明确指定Saxon的TransformerFactory类:
    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    TransformerFactory factory = TransformerFactory.newInstance();
    
  • 不要设置全局的单一StreamResult覆盖输出,Saxon会自动处理result-document生成的文件,只需确保输出目录有写入权限:
    // 错误写法:会强制输出到单一文件,覆盖result-document行为
    // transformer.transform(source, new StreamResult(new File("single-output.html")));
    
    // 正确写法:指定输出目录(或不指定,默认在当前目录生成多文件)
    transformer.transform(source, new StreamResult(new File("output-directory/")));
    

3. 修复页面跳转链接的路径一致性

确保页面内的跳转链接和result-document生成的文件名完全匹配:

  • 若生成的文件是page2.html,链接需写为<a href="page2.html">Page 2</a>
  • 若输出到子目录,需同步调整链接的相对路径,比如输出到docs/下,链接应为<a href="docs/page2.html">Page 2</a>

4. 调试验证步骤

  • 先用Saxon命令行工具测试转换,排除Java代码的干扰:
    java -jar saxon9he.jar -s:input.plmxml -xsl:your-stylesheet.xsl -o:output/
    
    查看output/目录下是否生成3个HTML文件,验证XSL逻辑是否正确。
  • 检查XSL中的循环/条件判断,确保result-document在每个需要生成独立页面的分支中都被触发,避免因逻辑错误导致仅执行一次。

内容的提问来源于stack exchange,提问作者ashish sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 20:15:22