Wednesday, November 23, 2005

Parsing an xml file without having access to the associated DTD

Pfffeww!
I have finally found the solution to my problem...
But lets start from the begin, well somewhat from the beginning.

I needed to change the logfile location as defined in a log4j.xml file from code.
So I started of with a DOM based solution using JDK1.4 features to parse the log4j.xml file, using jaxen to select nodes based on XPath expressions and then updating the found Node with the given value.

But... parsing the log4j.xml file failed because my application could not find the log4j.dtd file.
Removing the log4j.dtd file from the log4j.xml file solved the parsing problem but caused another problem, log4j would not accept the file anymore.
Also setting the validating flag to false did not solve the problem.

After searching the internet and trying several options, I found in the JBoss source code the solution, create inner class anonymous that implements the EntityResolver interface:
EntityResolver resolver = new EntityResolver () {
public InputSource resolveEntity (String publicId, String systemId) {
String empty = "";
ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
System.out.println("resolveEntity:" + publicId + "|" + systemId);
return new InputSource(bais);
}
};
builder.setEntityResolver(resolver);

The returned InputSource consists solely of an empty string, this satisfises loading the dtd, since validation is set to false, the read document is not validated.
Now lets see if is actaully correctly written back to disk.

10 comments:

Unknown said...

hey man
thanks alot for this entity resolver code
i struggled for 4 days to fix my xml issue which i used to compare with static and dyanic
now its dont with gr8 help from u r tips

SpiderMars said...

You're welcome, good to hear that even 2-year old posts can still be helpful.

Anonymous said...

Thanks for your post - it's still helpful (3 years after publication) ;)

Unknown said...

Thanks so much.

CM said...

Still helpful in 2010...

Thank you!!

Anonymous said...

Still helpful in the end of 2011!

Thanks

אראל סגל said...

Like an old wine :)

Thanks for saving me hours of frustration.

Anonymous said...

hey i tried for past 48 hours but in vain .i,m trying to parse an xml file using dom parser,jaxp.at dbs.parse() method file not found exception is thrown.i tried with entityresolver,and by setting flags false ie

dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
etc but failed to parse xml please guide me where im wrong

SpiderMars said...

Hi Anonymous,

I can only help out if you provide more information about the problem you're facing. Please provide at least a stack trace.

Dustin said...

Still helping people in late 2014. Well played.