将节点添加到根节点时的java.lang.NullPointerException

时间:2012-08-27 18:56:06

标签: java xml xml-parsing nullpointerexception

我试图通过以下函数将标记及其值动态添加到xml文件中。我正在尝试添加名为 first-name 的标记,并在根标记下添加值。但是在运行以下代码片段时,我会遇到异常。

    public void write(String name) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();            
        Document document = db.newDocument();

        Element blobKey_E = document.createElement("first-name");
        blobKey_E.appendChild( document.createTextNode( name ) );
        // The following line produces an exception
        // LINE 27 
        document.getDocumentElement().appendChild(blobKey_E); // append the new tag under the root

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File("/home/non-admin/NetBeansProjects/Personal Site_Testers/web/xml/xml_1.xml"));
        transformer.transform(source, result);            
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

例外:

java.lang.NullPointerException
at Beans.XmlBuilder.write(XmlBuilder.java:27)
at Servlets.tester.doGet(tester.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

我在上面的函数中突出显示第27行。

2 个答案:

答案 0 :(得分:1)

在这种情况下,

document.getDocumentElement()会返回null

getDocumentElement()的{​​{3}}表示以下功能是:

This is a convenience attribute that allows direct access to the child node that is the root element of the document. 

在您的情况下,您的DOM没有附加root element。您可能希望document.appendChild(blobKey_E);blobKey_E作为根元素附加到DOM。

理想情况下,当您尝试构建XML DOM时,以下是您需要遵循的基本步骤:

创建文档
创建根元素并将其添加到文档
创建子元素并将其附加到根或另一个现有子节点

public void write(String name) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();            
        Document document = db.newDocument();

        Element blobKey_E = document.createElement("first-name");
        blobKey_E.appendChild( document.createTextNode( name ) );

        /*
         * Here blobKey_E is treated as the root element for the document that you've created
         */
        document.appendChild(blobKey_E); 
//            // LINE 27 
//            document.getDocumentElement().appendChild(blobKey_E); // append the new tag under the root

        /*
         * Post this point, if you do a document.getDocumentElement(), it will no longer return 
         * a nullpointerexception because blobKey_E will be treated as the root element.
         */

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File("/home/non-admin/NetBeansProjects/Personal Site_Testers/web/xml/xml_1.xml"));
        transformer.transform(source, result);            
    }catch(Exception exc) {
        exc.printStackTrace();
    }
}

答案 1 :(得分:1)

document元素是您需要设置的根元素。将第27行更改为

document.appendChild(blobKey_E);