我尝试使用XPathFactory来评估Java应用程序中的表达式。但我得到了特定于撒克逊人的错误。有一段时间我使用Saxon来实现某些功能,为此,我必须设置一个系统属性:
System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
"net.sf.saxon.xpath.XPathFactoryImpl");
XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
但是,现在我只想使用默认DOM(org.w3c.dom.Document)进行一些XML处理并使用xpath进行处理,因此不需要Saxon。但是当我尝试创建XPathFactory时,我仍然会收到Saxon错误消息:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: net/sf/saxon/lib/EnvironmentVariableResolver
at net.sf.saxon.xpath.XPathFactoryImpl.<init>(XPathFactoryImpl.java:26)
...
我甚至试过&#34;重置&#34;系统属性:
System.setProperty("javax.xml.xpath.XPathFactory:",
"org.apache.xpath.jaxp.XPathFactoryImpl");
XPathFactory factory = XPathFactory.newInstance();
和
System.setProperty("javax.xml.xpath.XPathFactory:",
"http://java.sun.com/jaxp/xpath/dom");
XPathFactory factory = XPathFactory.newInstance();
但这并没有帮助,我仍然得到相同的错误信息。
如何再次使用默认的XPathFactory? (在我尝试使用Saxon之前,这个工作正常)
答案 0 :(得分:1)
作为一种解决方法,您可以明确地实现JDK工厂(或Xerces或Saxon&#39;)。
import org.apache.xpath.jaxp.XPathFactoryImpl
// import com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl
// import net.sf.saxon.xpath.XPathFactoryImpl
...
XPathFactory factory = new XPathFactoryImpl();
如果可能的话,更喜欢真正的Xerces实现,而不是JDK中的实现。它更可靠。
答案 1 :(得分:1)
我遇到了同样的问题。即使没有&#34; System.setProperty&#34;被调用,jaxp将加载saxon的xpath引擎作为默认实现,提示saxon jar在类路径上。参考:namespace-unaware XPath expression fails if Saxon is on the CLASSPATH。
我的解决方案:直接打电话给撒克逊:&#34; XPathFactory _xFactory = new net.sf.saxon.xpath.XPathFactoryImpl();&#34;并在类路径上的saxon9e.jar之前添加jaxen-xxx.jar和xercesImpl.jar。其他所有东西都保持其原始状态,没有调用&#34; System.setProperty&#34;。这对我有用。
我还测试了另一种方法如下:
System.setProperty("javax.xml.xpath.XPathFactory:" +XPathConstants.DOM_OBJECT_MODEL, "net.sf.saxon.xpath.XPathFactoryImpl");
XPathFactory xFactory = XPathFactory.newInstance(XPathConstants.DOM_OBJECT_MODEL);
System.setProperty(XPathFactory.DEFAULT_PROPERTY_NAME +":" + XPathFactory.DEFAULT_OBJECT_MODEL_URI, " org.apache.xpath.jaxp.XPathFactoryImpl");
XPathFactory xFactory2 = XPathFactory.newInstance();
System.out.println(xFactory.toString());
System.out.println(xFactory2.toString());
输出: net.sf.saxon.xpath.XPathFactoryImpl@71623278 com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl@768b970c 由于Jaxp使用apache的jaxen作为其默认的xpath实现,因此该方法应该是工具。 由于JAXP使用