Showing posts with label parsing. Show all posts
Showing posts with label parsing. Show all posts

Friday, June 5, 2009

Parsing XML with Commons Digester 2.0

Parsing XMLs with Commons Digester is no longer mystery or new. Probably one of the most easy and convenient way to parse XMLs. For more details, following links can be visited for very detailed explanation on XML parsing using commons digester...
As many occasions, this project of mine required parsing a XML configuration file and for that I took shelter of digester, but this time I upgraded to 2.0 from 1.8. With 2.0, digester provides XML schema validation support using javax.xml.validation.Schema. Below is the code snippet to use XML Schema while parsing the XML for ready reference...

// Load digester rules
Digester digester = DigesterLoader.createDigester( getClass().getClassLoader().getResource( digesterRules ) );

// XML Schema used for XML parsing
URI uri = getClass().getClassLoader().getResource( NOTES_XSD ).toURI();
Schema schema = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ).newSchema( new File( uri ) );
digester.setXMLSchema( schema );
digester.setNamespaceAware( true );
digester.setErrorHandler( myErrorHandler );

// XML file to parse
InputStream stream = getClass().getClassLoader().getResourceAsStream( FILE_TO_PARSE );
Object parse = digester.parse( stream );

With this you can get rid of your dependency on DTD and leverage power of XSD type support and better validation.

Cheers !!!
- Jay
Disclaimer : This is a personal blog and all content represent what I think and it does not advocate/support/advertise any other person/company. I do not earn money or intended to do so with this blog or any of the contents the blog hosts (except the google ads which you see). If I post something here that you find helpful, that's wonderful. Just in case, if I say something stupid, the stupidity is mine, and mine alone and I can not be held for anything if you fall for such stupidity :-). I cannot be held responsible for any kind of damage that may be caused by downloading or viewing the files or information provided herewith. Anybody and everybody can use/refer the contents of this blog at their own will and of course at own risk. There is no need for any kind of approval of the author. Although it would be great if feedback is left for any such usage to the author.