好的,这是对我有用的答案。
第一步:加载原始文档,关闭工厂内的验证和 dtd 加载。
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// stop the network loading of DTD files
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setFeature("http://xml.org/sax/features/namespaces", false);
factory.setFeature("http://xml.org/sax/features/validation", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// open up the xml document
DocumentBuilder docbuilder = factory.newDocumentBuilder();
Document doc = docbuilder.parse(new FileInputStream(m_strFilePath));
第二步:现在我已经将文档存储在内存中......并且在检测到我需要转换它之后 -
TransformerFactory transformfactory = TransformerFactory.newInstance();
Templates xsl = transformfactory.newTemplates(new StreamSource(new FileInputStream((String)m_XslFile)));
Transformer transformer = xsl.newTransformer();
Document newdoc = docbuilder.newDocument();
Result XmlResult = new DOMResult(newdoc);
// now transform
transformer.transform(
new DOMSource(doc.getDocumentElement()),
XmlResult);
我需要这样做,因为我之后要进行进一步的处理,并且不希望产生输出到文件和重新加载的开销。
小解释:
诀窍是使用已关闭所有验证功能的原始 DOM 对象。你可以在这里看到这个:
transformer.transform(
new DOMSource(doc.getDocumentElement()), // <<-----
XmlResult);
这已经在网络访问关闭的情况下进行了测试。
所以我知道不再有网络查找。
但是,如果 DTD、MOD 等在本地可用,那么根据建议,使用 EntityResolver 就是答案。这将再次应用于原始内容文档生成器 object.
我现在有一个转换后的文档存储在newdoc,准备玩了。
我希望这会帮助其他人。