Java parse XML file reads local DTD or ignores DTD

Source: Internet
Author: User
Tags xml parser

When the Java program parses the XML file, if the DTD is specified in the XML file, the DTD file is downloaded from the specified URL by default, but in many cases, if the network is not connected, or because of a firewall reason, the DTD file cannot be downloaded to cause the report connection timeout exception and parsing the XML fails. There are two ways to solve this type of problem:

1. Specify to read the DTD file locally

The XML file to parse has the following DTD declaration:.

<! DOCTYPE concept Public "-//oasis//dtd DITA concept//en" "http://docs.oasis-open.org/dita/v1.2/os/dtd1.2/ Technicalcontent/dtd/concept.dtd ">

PUBLICID: The public identifier of the referenced external entity, or null if it is not provided.

The above DTD declaration publicid as-//oasis//dtd DITA concept//en

SystemID: The system identifier of the referenced external entity.

SystemID as HTTP://DOCS.OASIS-OPEN.ORG/DITA/V1.2/OS/DTD1.2/TECHNICALCONTENT/DTD/CONCEPT.DTD in the DTD declaration above

You can throws Saxexception by ResolveEntity (string publicid, String systemid) of the Entityresolver class of sax. The IOException method specifies that a local DTD file be read, which is called before the XML parser parses the XML to load the specified DTD file:

/**
 * Implementation of <code>org.xml.sax.EntityResolver</code> that loads
 * Entitities (for Example DTD files) from the classpath.
 */Public
class Classpathentityresolver
    implements Entityresolver
{public

    InputSource ResolveEntity (String publicid, String systemid)
        throws Saxexception, IOException
    {
    	
        if (systemid null) c10/>{
            
            int index = systemid.lastindexof ('/');
            if (index!=-1)
            {
            	SystemID = systemid.substring (index + 1);
            }
            SystemID = "/" + SystemID;
            InputStream ISTR = Thread.CurrentThread (). Getcontextclassloader (). getResourceAsStream (systemId);
            if (ISTR!= null)
            {return
                new InputSource (ISTR);
            }
        }
        return null;
    }
}
Specify the custom Classpathentityresolver before sax parses the XML file:

SAXParserFactory SPF = saxparserfactory.newinstance ();
SAXParser saxparser = Spf.newsaxparser ();
	    
XmlReader = Saxparser.getxmlreader ();
Xmlreader.setentityresolver (New Classpathentityresolver ());
Xmlreader.setcontenthandler (handler);
try {
	xmlreader.parse (new InputSource (Inputfilepath));
	} catch (Exception e) {
		e.printstacktrace ();
	}

Note: Regular testing has found that this method is only valid for system (local DTD), such as:

<! DOCTYPE concept SYSTEM "HTTP://DOCS.OASIS-OPEN.ORG/DITA/V1.2/OS/DTD1.2/TECHNICALCONTENT/DTD/CONCEPT.DTD" >

However, it does not work for public (external DTDs), such as:

<! DOCTYPE concept Public "-//oasis//dtd DITA concept//en" "http://docs.oasis-open.org/dita/v1.2/os/dtd1.2/ Technicalcontent/dtd/concept.dtd ">

The public DTD still downloads the DTD from the outside, and the DTD checksum can only be ignored in the second way.


2. Completely ignore DTDs when parsing XML files:

The SAX parser can determine whether to ignore DTDs by specifying the Http://apache.org/xml/features/nonvalidating/load-external-dtd property, as shown in the following example:

SAXParserFactory SPF = saxparserfactory.newinstance ();
SAXParser saxparser = Spf.newsaxparser ();
	    
XmlReader = Saxparser.getxmlreader ();
Xmlreader.setfeature ("Http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
Xmlreader.setcontenthandler (handler);
try {
	xmlreader.parse (new InputSource (Inputfilepath));
	} catch (Exception e) {
		e.printstacktrace ();
	}
After this is specified, DTD validation is no longer performed when parsing the XML file.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.