2012-03-28 23 views
19

我想使用JAXB unmashall一些XML,我首先使用xjc创建。我不想对解组进行任何验证,但即使我已根据与u.setSchema(null);的JAXB文档禁用了验证,但这并未阻止FileNotFoundException在尝试运行时发生,并且无法找到架构。如何使用JAXB2.0禁用DTD提取

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

我已经看到了致残SAX由Apache属性设置http://apache.org/xml/features/validation/schemafalse从验证分析类似的问题,但我不能让着Unmarshaller用自己的SAX解析器。

回答

7

以下是一个演示如何获得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()); 
    } 

} 
+9

,对我没有工作,但这些丝毫:parser.setFeature(“HTTP: //apache.org/xml/features/nonvalidating/load-external-dtd“,false); parser.setFeature(“http://xml.org/sax/features/validation”,false); – aerobiotic 2012-05-25 22:13:40

+0

有氧生物是正确的 – sura2k 2014-06-17 08:08:12

+0

[This](https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#SAXTransformerFactory)网站解释了它如何在任何主要的Java框架上被阻塞。 – 2016-08-10 20:50:34

15

大厦从@布莱斯 - 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); 
    } 
} 
+0

这对我有用。另外还增加了'spf.setValidating(false);'谢谢 – gihan 2016-11-29 07:00:04