Skip to content

Instantly share code, notes, and snippets.

@rbe
Created October 22, 2010 06:28
Show Gist options
  • Save rbe/640050 to your computer and use it in GitHub Desktop.
Save rbe/640050 to your computer and use it in GitHub Desktop.
package com.bensmann.xml
class CachedDTD {
/**
* Return DTD 'systemId' as InputSource.
* @param publicId
* @param systemId
* @return InputSource for locally cached DTD.
*/
def static entityResolver = [
resolveEntity: { publicId, systemId ->
try {
new org.xml.sax.InputSource(CachedDTD.class.getResourceAsStream("dtd/" + systemId.split("/").last()))
} catch (e) {
e.printStackTrace()
null
}
}
] as org.xml.sax.EntityResolver
}
package com.bensmann.xml;
import java.io.IOException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class CachedDTD implements EntityResolver {
/**
* Return DTD 'systemId' as InputSource.
* @param publicId
* @param systemId
* @return InputSource for locally cached DTD.
*/
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
String[] resource = systemId.split("/");
try {
InputStream uri = CachedDTD.class.getResourceAsStream("dtd/" + resource[resource.length - 1]);
return new InputSource(uri);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
// Create instance of XmlSlurper and set EntityResolver
def slurper = new XmlSlurper()
slurper.setEntityResolver(com.bensmann.xml.CachedDTD.entityResolver)
// Parse UTF-8 XML file
slurper.parseText(new File("/Users/rbe/example.xml").getText("UTF-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment