Created
October 22, 2010 06:28
-
-
Save rbe/640050 to your computer and use it in GitHub Desktop.
Use local DTD for XML parsing, http://blog.bensmann.com/http-503-when-parsing-xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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