我正在使用StAX读取XML内容,并通过从StAXSource转换为DOMResult将其中的部分内容解析为DOM片段。但是,当任何元素重新定义默认XML命名空间(xmlns =“”)时,这会导致NullPointerException。用于演示这种情况的最小代码:
String xml =
"<?xml version=\"1.0\"?>"+
"<document>"+
" <element xmlns=\"\" />"+
"</document>";
StringReader reader = new StringReader(xml);
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(reader);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
StAXSource source = new StAXSource(xsr);
DOMResult result = new DOMResult();
t.transform(source,result);
stacktrace的开头是:
Caused by: java.lang.NullPointerException
at com.sun.org.apache.xml.internal.serializer.NamespaceMappings.pushNamespace(NamespaceMappings.java:233)
at com.sun.org.apache.xml.internal.serializer.ToXMLSAXHandler.startPrefixMapping(ToXMLSAXHandler.java:362)...
根据我的理解,输入XML是有效的。 Woodstox实现可以毫无问题地转换XML,但如果有方法可以配置或解决与Java捆绑的默认实现的问题,我宁愿不向我的应用程序添加更多依赖项。有什么办法吗?或者这应该被视为Java默认实现中的错误?
答案 0 :(得分:0)
使用有效的xml文件
尝试更改代码
XMLInputFactory xif = XMLInputFactory.newInstance();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("test.xml"));
xsr.nextTag();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
DOMResult result = new DOMResult();
t.transform(new StAXSource(xsr), result);
Node domNode = result.getNode();
}
答案 1 :(得分:0)
我建议使用SAX,即使使用xmlns =“”
也能正常工作XMLReader xr = XMLReaderFactory.createXMLReader();
Source source = new SAXSource(xr, new InputSource(reader));