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

后端 未结 5 1952
自闭症患者
自闭症患者 2020-11-30 10:21

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.

5条回答
  •  情深已故
    2020-11-30 10:51

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

提交回复
热议问题