我正在尝试使用 JAXB 来解码我最初使用 xjc 创建的一些 XML。我不想对解码进行任何验证,但即使我根据 JAXB 文档使用 u.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 解析>,但我无法让 Unmarshaller 使用我自己的 sax 解析器。
最佳答案
基于@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);
}
}
关于java - 如何使用 JAXB2.0 禁用 DTD 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9909465/