Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SAX Parser raises UnknownHostException

Tags:

java

dtd

sax

The XML file I want to parse starts with :

<!DOCTYPE plist PUBLIC "-//...//DTD PLIST 1.0//EN" "http://www.....dtd">

So when I start the SAX praser, it tries to access this DTD online, and I get a java.net.UnknownHostException.

  1. I cannot modify the XML file before feeding it to the SAX parser
  2. I have to run even with no internet connection

How can I change the SAX Parser behaviour so that it does not try to load the DTD ? Thanks.

javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setValidating(false);

javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.parse(xmlFile, handler);
like image 900
Eric Nicolas Avatar asked Nov 17 '08 15:11

Eric Nicolas


2 Answers

Ok, turns out the parse() method overrides any previously set entity resolvers with the handler passed in to the parse method. The following code should work:

javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setValidating(false);
javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.parse(new java.io.File("x.xml"), new org.xml.sax.helpers.DefaultHandler(){
        public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)
                throws org.xml.sax.SAXException, java.io.IOException {
            System.out.println("Ignoring: " + publicId + ", " + systemId);
            return new org.xml.sax.InputSource(new java.io.StringReader(""));
        }
    }); 
like image 140
Gowri Avatar answered Oct 10 '22 02:10

Gowri


Use XMLReader instead of SAXParser.

    XMLReader reader =XMLReaderFactory.createXMLReader();
 reader.setEntityResolver(new DummyEntityResolver());
    reader.setContentHandler(handler);
 reader.parse(inputSource);

It should also work with SAXParser, but for some reasons it doesn't.

like image 40
Stefano Rosanelli Avatar answered Oct 10 '22 02:10

Stefano Rosanelli