我正在尝试使用 Saxon 运行“不同值”XPath。这是我的代码:
@Test
public void testAttributeSelect() throws XPathFactoryConfigurationException {
System.setProperty("javax.xml.xpath.XPathFactory:"
+ NamespaceConstant.OBJECT_MODEL_SAXON,
"net.sf.saxon.xpath.XPathFactoryImpl");
System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
"net.sf.saxon.dom.DocumentBuilderFactoryImpl");
String xpathString = "distinct-values(//id)";
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
try {
DocumentBuilder builder = domFactory.newDocumentBuilder();
System.out.println(builder.getClass());
Document doc =
builder.parse(this.getClass().getResourceAsStream("parametrizedId_feed.xml"));
System.out.println(doc.getClass());
XPath xpath =
XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON).newXPath();
NodeList s1 = (NodeList)
xpath.evaluate("/matches", doc, XPathConstants.NODESET);
NodeList s = (NodeList)
xpath.evaluate(xpathString, s1 , XPathConstants.NODESET);
我得到这个异常:
javax.xml.xpath.XPathExpressionException: Cannot locate an object model implementation for nodes of class net.sf.saxon.dom.DOMNodeList at net.sf.saxon.xpath.XPathExpressionImpl.evaluate(XPathExpressionImpl.java:300) at net.sf.saxon.xpath.XPathEvaluator.evaluate(XPathEvaluator.java:434) at ca.cbc.panacea.playground.TestXpath.testAttributeSelect(TestXpath.java:43) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
Saxon-dom jar 文件位于类路径中。 另外,如果我尝试直接在 doc 对象上调用“不同值”,我会得到:
net.sf.saxon.trans.XPathException: Extension function required class org.w3c.dom.NodeList; supplied value of class net.sf.saxon.value.UntypedAtomicValue could not be converted at net.sf.saxon.dom.DOMObjectModel.convertXPathValueToObject(DOMObjectModel.java:395) at net.sf.saxon.dom.DOMObjectModel.access$000(DOMObjectModel.java:42) at net.sf.saxon.dom.DOMObjectModel$5.convert(DOMObjectModel.java:166) at net.sf.saxon.xpath.XPathExpressionImpl.evaluate(XPathExpressionImpl.java:352) at net.sf.saxon.xpath.XPathEvaluator.evaluate(XPathEvaluator.java:434)
我不明白这里发生了什么。谷歌也没有!
最佳答案
首先要指出的是,DOM 和 Saxon 并不能很好地结合在一起。如果您构建树是为了在其上使用 Saxon,请优先使用 Saxon 的 native 树模型而不是 DOM - 速度快十倍。
您提到 saxon-dom.jar 的事实意味着您必须使用相当旧的 Saxon 版本,可能不再受支持。因此,我的下一个建议是转向更新的版本。
我注意到的另一件事是,您要求使用 XPath 处理器来处理 Saxon 对象模型,然后使用它来处理 DOM 对象模型。我不知道这是否可行。 (如果您想确保加载 Saxon 而不是其他 XPath 引擎,例如因为您需要 XPath 2.0,那么最好完全跳过 JAXP 工厂机制,直接实例化 Saxon 实现。)
关于java - 撒克逊不同值抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8045696/