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


can you expound the code parsing a specific sample pojo? and also i don't understand the "DigesterLoader.createDigester" section what object you call "getClass()". Also how did you create the "digesterRules" object. Thanks
ReplyDeletecan you expound the code parsing a specific sample pojo? and also i don't understand the "DigesterLoader.createDigester" section what object you call "getClass()". Also how did you create the "digesterRules" object. Thanks
ReplyDelete@ Keith, I've the digester rules file (digesterRules) in my classpath, which am loading using the classloader of runtime class of the object. This helps me keeping my digester rules as separate configuration and also I can package it with my jar/war/ear. So digesterRules is a simple String which looks something like (com/jak/digester/config/digester-rules.xml)
ReplyDeleteFor full blown example of Digester please visit one of the links I mentioned in the start of my post.