Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read well formed XML in Java, but skip the schema?

Tags:

java

xml

I want to read an XML file that has a schema declaration in it.

And that's all I want to do, read it. I don't care if it's valid, but I want it to be well formed.

The problem is that the reader is trying to read the schema file, and failing.

I don't want it to even try.

I've tried disabling validation, but it still insists on trying to read the schema file.

Ideally, I'd like to do this with a stock Java 5 JDK.

Here's what I have so far, very simple:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);

and here's the exception I am getting back:

java.lang.RuntimeException: java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd

Yes, this HAPPENS to be an XHTML schema, but this isn't an "XHTML" issue, it's an XML issue. Just pointing that out so folks don't get distracted. And, in this case, the W3C is basically saying "don't ask for this thing, it's a silly idea", and I agree. But, again, it's a detail of the issue, not the root of it. I don't want to ask for it AT ALL.

like image 958
Will Hartung Avatar asked Jul 26 '09 20:07

Will Hartung


People also ask

How do I read an XML string in Java?

In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.


1 Answers

The reference is not for Schema, but for a DTD.

DTD files can contain more than just structural rules. They can also contain entity references. XML parsers are obliged to load and parse DTD references, because they could contain entity references that might affect how the document is parsed and the content of the file(you could have an entity reference for characters or even whole phrases of text).

If you want to want to avoid loading and parsing the referenced DTD, you can provide your own EntityResolver and test for the referenced DTD and decide whether load a local copy of the DTD file or just return null.

Code sample from the referenced answer on custom EntityResolvers:

   builder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId)
                throws SAXException, IOException {
            if (systemId.contains("foo.dtd")) {
                return new InputSource(new StringReader(""));
            } else {
                return null;
            }
        }
    });
like image 85
Mads Hansen Avatar answered Oct 17 '22 18:10

Mads Hansen