• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 863
  • Last Modified:

Validating xml documents using external DTD's

Hello Experts,

In my application i am parsing xml files which includes dtd file path in DOCTYPE declaration. I do not want parser to use the dtd file which is reffered in same xml file, instead of that I would like to pass dtd file path from java program.
I have done lot of googling and come to know that it could be done by entityResolver. However, the problem is that when I am passing path from the application it gives error during validation like below...

"The markup declarations contained or pointed to by the document type declaration must be well-formed."

The piece of code I am using looks like;

public class TestValidation extends DefaultHandler implements EntityResolver {

//---custom dtd file to set for validation------
public static String customDTD= "../../../demo/dtdFile/test.dtd";

//-----------Here validation xml file private static void validatePackages(XML xmlFileName) throws IOException, ParserConfigurationException, SAXException {

TestValidation errorHandler = new TestValidation ();

SAXParserFactory factory = SAXParserFactory.newInstance();


try {

SAXParser parser = factory.newSAXParser();
if(!xmlFileName.exists()) {
System.err.println("Did not find file ");
parser.parse(f, errorHandler);

}finally {



//-------------------Checking for dtd file given in xml file if yes then setting it to custom file----------------------------

public InputSource resolveEntity(String publicId, String systemId)

if (systemId.contains(".dtd")){
System.out.println("publicId="publicId" systemId="+systemId );

return new InputSource(new ByteArrayInputStream(customDTD.getBytes()));

System.out.println("Other tag found");
return null;

public void error(SAXParseException e) throws SAXParseException {

---- Handling errors found;


I think the way I am providing dtd file path is wrong.
Can you please suggest the modified code for this?

1 Solution
Note : This is just a workaround to the above problem.  For all, please ignore the following solution and reply to the actual question posted by ShaileshShinde.

Read the file using FileReader and replace the 'doctype' declaration with your required data and create an intermediate temp .xml file.

Now read the above temp xml file.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now