How to disable DTD fetching using JAXB2.0

前端 未结 5 1882
执念已碎
执念已碎 2020-12-02 17:54

I\'m trying to use JAXB to unmashall some XML which I used xjc to create in the first place. I don\'t want to do any validation on the unmarshalling, but even though I have

5条回答
  •  -上瘾入骨i
    2020-12-02 18:09

    Building on the answers from @blaise-doughan and @aerobiotic, here is a solution that worked for me:

    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);
        }
    }
    

提交回复
热议问题