code_junkie

how to disable dtd at runtime in java's xpath?

Nov 11th, 2011
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. <?xml version="1.0"?>
  2. <!DOCTYPE foo PUBLIC "//FOO//" "foo.dtd">
  3. <foo>
  4. <bar>Value</bar>
  5. </foo>
  6.  
  7. import java.io.File;
  8. import java.io.IOException;
  9. import java.io.StringReader;
  10.  
  11. import javax.xml.parsers.DocumentBuilder;
  12. import javax.xml.parsers.DocumentBuilderFactory;
  13. import javax.xml.xpath.XPath;
  14. import javax.xml.xpath.XPathFactory;
  15.  
  16. import org.w3c.dom.Document;
  17. import org.xml.sax.EntityResolver;
  18. import org.xml.sax.InputSource;
  19. import org.xml.sax.SAXException;
  20.  
  21. public class Main {
  22.  
  23. public static void main(String[] args) throws Exception {
  24. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  25. DocumentBuilder builder = factory.newDocumentBuilder();
  26.  
  27. builder.setEntityResolver(new EntityResolver() {
  28.  
  29. @Override
  30. public InputSource resolveEntity(String publicId, String systemId)
  31. throws SAXException, IOException {
  32. System.out.println("Ignoring " + publicId + ", " + systemId);
  33. return new InputSource(new StringReader(""));
  34. }
  35. });
  36. Document document = builder.parse(new File("src/foo.xml"));
  37. XPathFactory xpathFactory = XPathFactory.newInstance();
  38. XPath xpath = xpathFactory.newXPath();
  39. String content = xpath.evaluate("/foo/bar/text()", document
  40. .getDocumentElement());
  41. System.out.println(content);
  42. }
  43. }
  44.  
  45. SAXParserFactory saxfac = SAXParserFactory.newInstance();
  46. saxfac.setValidating(false);
  47. try {
  48. saxfac.setFeature("http://xml.org/sax/features/validation", false);
  49. saxfac.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
  50. saxfac.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
  51. saxfac.setFeature("http://xml.org/sax/features/external-general-entities", false);
  52. saxfac.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
  53. }
  54. catch (Exception e1) {
  55. e1.printStackTrace();
  56. }
  57.  
  58. <!DOCTYPE root-element SYSTEM "filename">
Add Comment
Please, Sign In to add comment