使用DocumentBuilder在java中解析XML后将文档获取为null[#document:null]
解析完文档后,我得到了null,即使文档包含数据。 这是我的代码,我已将所有验证设置为false使用DocumentBuilder在java中解析XML后将文档获取为null[#document:null],xml,null,document,Xml,Null,Document,解析完文档后,我得到了null,即使文档包含数据。 这是我的代码,我已将所有验证设置为false DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(false); // never forget this! domFactory.setCoalescing(false); domFactory.setValidati
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(false); // never forget this!
domFactory.setCoalescing(false);
domFactory.setValidating(false);
domFactory.setFeature("http://xml.org/sax/features/namespaces", false);
domFactory.setFeature("http://xml.org/sax/features/validation", false);
domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
domFactory.setFeature("http://apache.org/xml/features/allow-java-encodings",
true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
builder.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(java.lang.String publicId, java.lang.String systemId)
throws SAXException, java.io.IOException {
if (publicId.equals("--myDTDpublicID--"))
// this deactivates the open office DTD
return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
else return null;
}
});
Document doc = null;
URL url = new URL(urlStr);
URLConnection urlc = url.openConnection();
doc = builder.parse(urlc.getInputStream());
System.out.println("doc:" + doc.toString());
为什么??
是否缺少一些验证?[#文档:null]
只是文档
实例的toString,它不会输出整个XML文档
实例本身不是空的,您可能可以毫无问题地继续处理。您应该向文档对象添加静态修饰符,我也遇到了同样的问题,在解析操作之后,所有非静态对象都只是引用空。使其成为静态会迫使java在变量中的解析操作期间保留对已创建对象的引用。我认为此链接可以回答您的问题。
doc:[#document: null]