我在以下代码中得到 NullPointerException:
String str = SOME_HTML_STRING;
Node node = convertStrIntoNodeUsingJTidy();
domToString(node);
//converts node to string
public static String domToString(org.w3c.dom.Node node)throws Exception {
try {
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// NullPointerException at this line, although node is not null
transformer.transform(new DOMSource(node), new StreamResult(sw));
return sw.toString();
} catch (Exception ex) {
throw new Exception("Error converting to String", ex);
}
}
堆栈跟踪是:
Caused by: javax.xml.transform.TransformerException: java.lang.NullPointerException
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(Unknown Source)
at com.example.Util.domToString(Util.java:3179)
... 128 more
Caused by: java.lang.NullPointerException
at com.sun.org.apache.xml.internal.serializer.ToXMLStream.processingInstruction(Unknown Source)
at com.sun.org.apache.xml.internal.serializer.ToUnknownStream.processingInstruction(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(Unknown Source)
... 131 more
我已经检查了以下链接: http: //geekymeeky.blogspot.in/2008/10/javaxxmltransform-transformerexception.html
上面的帖子说,如果文本节点为空,则会发生此异常。
我想知道,变量str的什么值导致文本节点值为 null 并导致此异常。