Java, xml, XSLT: Prevent DTD-Validation

前端 未结 5 1329
醉酒成梦
醉酒成梦 2020-12-16 06:28

I use the Java (6) XML-Api to apply a xslt transformation on a html-document from the web. This document is wellformed xhtml and so contains a valid DTD-Spec (

5条回答
  •  眼角桃花
    2020-12-16 06:41

    I recently had this issue while unmarshalling XML using JAXB. The answer was to create a SAXSource from an XmlReader and InputSource, then pass that to the JAXB UnMarshaller's unmarshal() method. To avoid loading the external DTD, I set a custom EntityResolver on the XmlReader.

    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xmlr = sp.getXMLReader();
    xmlr.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String pid, String sid) throws SAXException {
            if (sid.equals("your remote dtd url here"))
                return new InputSource(new StringReader("actual contents of remote dtd"));
            throw new SAXException("unable to resolve remote entity, sid = " + sid);
        } } );
    SAXSource ss = new SAXSource(xmlr, myInputSource);
    

    As written, this custom entity resolver will throw an exception if it's ever asked to resolve an entity OTHER than the one you want it to resolve. If you just want it to go ahead and load the remote entity, remove the "throws" line.

提交回复
热议问题