Ignoring DTD in XMLUnit

XMLUnit uses Validator class to validate XML format. The default is to validate against a DTD. Validating against a DTD is straight forward if the piece of XML contains a DOCTYPE declaration with a SYSTEM identifier that can be resolved at validation time. However, DTD may not always be available when you test the XML files. In such case, you need to ignore DTD validation and just check whether the XML file is well-formed. To do so, we need to create a new DocumentBuilderFactory, and disable the validation function.

Here is the code:

 // don't validate dtd
 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 dbf.setValidating(false);
 try {
   dbf.setFeature("http://xml.org/sax/features/namespaces", false);
   dbf.setFeature("http://xml.org/sax/features/validation", false);
   dbf.setFeature(
       "http://apache.org/xml/features/nonvalidating/load-dtd-grammar",
       false);
   dbf.setFeature(
       "http://apache.org/xml/features/nonvalidating/load-external-dtd",
       false);
 } catch (ParserConfigurationException e) {
   e.printStackTrace();
 }
 
 XMLUnit.setTestDocumentBuilderFactory(dbf);
 XMLUnit.setControlDocumentBuilderFactory(dbf);
Category >> Library  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>