Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

java - How to disable DTD fetching using JAXB2.0

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 disabled the validation according to the JAXB documentation with u.setSchema(null);, but this hasn't prevented a FileNotFoundException being thrown when it tries to run and can't find the schema.

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

I've seen similar questions for disabling SAX parsing from validation by setting the apache property http://apache.org/xml/features/validation/schema to false, but I can't get the Unmarshaller to use my own sax parser.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...