我在使用以下代码时遇到了一些烦人的问题,直到切换到Java 1.7才能正常工作
import javax.xml.validation.SchemaFactory;
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
使用-Djaxp.debug = 1从Netbeans运行时,会引发以下错误:
上面的剪辑代码是OSGI包的一部分
JAXP: using thread context class loader (sun.misc.Launcher$AppClassLoader@5e3a78ad) for search
JAXP: Looking up system property 'javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema'
JAXP: The property is undefined.
JAXP: found null in $java.home/jaxp.properties
JAXP: no META-INF/services/javax.xml.validation.SchemaFactory file was found
JAXP: attempting to use the platform default XML Schema validator
JAXP: instanciating org.apache.xerces.jaxp.validation.XMLSchemaFactory
JAXP: failed to instanciate org.apache.xerces.jaxp.validation.XMLSchemaFactory
java.lang.ClassNotFoundException: org.apache.xerces.jaxp.validation.XMLSchemaFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at javax.xml.validation.SchemaFactoryFinder.createInstance(Unknown Source)
at javax.xml.validation.SchemaFactoryFinder._newFactory(Unknown Source)
at javax.xml.validation.SchemaFactoryFinder.newFactory(Unknown Source)
at javax.xml.validation.SchemaFactory.newInstance(Unknown Source)
JAXP: unable to find a factory for http://www.w3.org/2001/XMLSchema
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: http://www.w3.org/2001/XMLSchema
我还制作了一个只有工厂实例的小型Java应用程序
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
工厂是" com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory" 的实例,而在我的捆绑包中它试图实例化 " org.apache.xerces.jaxp.validation.XMLSchemaFactory" (可能无法找到它)。
为什么会出现这种差异? 什么似乎是问题,任何想法?
答案 0 :(得分:0)
这项工作对我来说是JRE 7:
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new SAXSource(new InputSource(new ByteArrayInputStream(xsd.getBytes()))));
Validator validator = schema.newValidator();
validator.validate(new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes()))));
System.out.println("Validated !");
答案 1 :(得分:0)
我通过使用Thread Context Class Loader(通常缩写为TCCL)来实现这一点。这是代码:
ClassLoader original = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(ClassWithinYourBundle.class.getClassLoader());
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
} finally {
Thread.currentThread().setContextClassLoader(original);
}
适当地更换ClassWithinYourBundle
。
有关详细信息,请参阅GitHub Project。
有关TCCL的更多信息,请参阅:https://articles.qos.ch/classloader.html