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

JDK 11中从XALAN迁移至SAXON库的实现求助

将Xalan替换为Saxon的实现方案(JDK 11环境)

一、依赖调整(pom.xml)

首先移除Xalan依赖,仅保留Saxon-HE即可,修改后的pom.xml如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>TESTsingle</groupId>
    <artifactId>single</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>net.sf.saxon</groupId>
            <artifactId>Saxon-HE</artifactId>
            <version>11.4</version>
            <exclusions>
                <exclusion>
                    <groupId>xml-apis</groupId>
                    <artifactId>xml-apis</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
</project>

二、代码重构

Saxon的XPath API与Xalan的XPathAPI工具类用法差异较大,需通过Saxon核心组件实现节点查询,以下是重构后的完整代码:

import net.sf.saxon.s9api.*;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Main {

    public static void main(String[] args) throws SaxonApiException {
        // 可在此添加示例调用逻辑
    }

    NodeList extractNodeList(Element ele) throws SaxonApiException {
        // 初始化Saxon核心处理器
        Processor processor = new Processor(false);
        XPathCompiler xpathCompiler = processor.newXPathCompiler();

        // 编译目标XPath表达式
        XPathExecutable executable = xpathCompiler.compile("//Products");

        // 将W3C Element转换为Saxon兼容的NodeInfo节点
        DocumentBuilder docBuilder = processor.newDocumentBuilder();
        NodeInfo contextNode = docBuilder.wrap(ele);

        // 绑定上下文节点并执行查询
        XPathSelector selector = executable.load();
        selector.setContextItem(contextNode);
        XdmValue result = selector.evaluate();

        // 将Saxon查询结果转换为W3C标准NodeList,适配原有返回类型
        return processor.getUnderlyingConfiguration()
                .getDocumentBuilder()
                .build(result)
                .getDocumentElement()
                .getChildNodes();
    }
}

关键细节说明

  • 核心组件作用:
    • Processor:Saxon的核心入口,负责初始化运行环境
    • XPathCompiler:编译XPath表达式,支持XPath 2.0+语法特性
    • XPathSelector:绑定查询上下文节点并执行表达式
  • 节点类型转换:必须将W3C的Element转换为Saxon的NodeInfo,才能作为查询的上下文节点
  • 结果适配:Saxon返回的XdmValue需转换为W3C标准的NodeList,确保原有代码的兼容性

三、额外注意事项

  • 原XPath表达式//Products完全兼容Saxon的语法规则,无需修改
  • 若需使用复杂XPath特性(如自定义函数、命名空间),可通过XPathCompiler进行配置
  • 确保项目中无其他依赖引入Xalan,避免类加载冲突

内容的提问来源于stack exchange,提问作者Suman Shekhar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:55:18