如何使用JAXB2.0禁用DTD获取

我正在尝试使用JAXB取消一些我首先使用xjc创建的XML。 我不想对解组进行任何validation,但即使我根据JAXB文档使用u.setSchema(null);禁用了validationu.setSchema(null); ,但这并没有阻止在尝试运行并且找不到架构时抛出FileNotFoundException

 JAXBContext jc = JAXBContext.newInstance("blast"); Unmarshaller u = jc.createUnmarshaller(); u.setSchema(null); return u.unmarshal(blast) 

我已经看到类似的问题,通过将apache属性http://apache.org/xml/features/validation/schema设置为false来禁用SAX解析validation,但是我无法让Unmarshaller使用我自己的sax解析器。

下面是演示如何使用JAXB(JSR-222)实现来使用SAX解析器的示例代码:

 import java.io.FileReader; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Foo.class); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource(new FileReader("input.xml")); SAXSource source = new SAXSource(xmlReader, inputSource); Unmarshaller unmarshaller = jc.createUnmarshaller(); Foo foo = (Foo) unmarshaller.unmarshal(source); System.out.println(foo.getValue()); } } 

基于@ blaise-doughan和@aerobiotic的答案,这是一个对我有用的解决方案:

 import java.io.FileReader; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; public class Demo2 { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(MyBean.class); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); spf.setFeature("http://xml.org/sax/features/validation", false); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource( new FileReader("myfile.xml")); SAXSource source = new SAXSource(xmlReader, inputSource); Unmarshaller unmarshaller = jc.createUnmarshaller(); MyBean foo = (MyBean) unmarshaller.unmarshal(source); } } 

您可以直接从javax.xml.transform.sax.SAXSource创建Unmarshaller。

请参阅此页面上的示例: http : //docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/api/javax/xml/bind/Unmarshaller.html

比你“只”需要为SAXSource提供你自己的URIResolver

查看此资源https://java.net/projects/jaxb/lists/users/archive/2003-11/message/60当最佳答案无效时,它对我有用。