我正在尝试将dom节点转换为具有以下代码的字节(jdk1.8.0_40):
DOMImplementationLS domImplementationLS = (DOMImplementationLS) (node instanceof Document ? ((Document) node) : node.getOwnerDocument()).getImplementation().getFeature("LS", "3.0");
LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
lsSerializer.getDomConfig().setParameter("format-pretty-print", prettyPrint);
LSOutput lsOutput = domImplementationLS.createLSOutput();
lsOutput.setEncoding(UTF_8.toString());
ByteArrayOutputStream writer = new ByteArrayOutputStream();
lsOutput.setByteStream(writer);
lsSerializer.write(node, lsOutput);
这导致NPE:
org.w3c.dom.ls.LSException
at com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.write(DOMSerializerImpl.java:844)
java.lang.NullPointerException
at com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.prepareForSerialization(DOMSerializerImpl.java:1063)
at com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.write(DOMSerializerImpl.java:747) ... 40 more
这是java中的错误还是我做错了什么?
更新: 我发现当我得到文档元素时它可以工作:
lsSerializer.write((node instanceof Document ? ((Document) node) : node.getOwnerDocument()), lsOutput);
java doc声明:要序列化的节点,但似乎这不是Document节点。