简体   繁体   中英

java.lang.NullPointerException while adding node to the root node

I am trying to add a tag and it's value dynamically into the xml file through the following function.I am trying to add the tag named first-name and it value under the root tag. But while running the following snippet I am getting exceptions.

    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();
    }
}

exceptions :

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)

I have highlighted line number 27 in the function above.

document.getDocumentElement() in this case returns null

The Javadoc for getDocumentElement() says the following about is functionality:

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

In your case, there is no root element attached to your DOM. You may want to do a document.appendChild(blobKey_E); to attach blobKey_E to the DOM as the root element.

Ideally when you're trying to build up an XML DOM, here're the basic steps that you would need to follow:

Create Document
Create the root element and add it to the Document
Create child elements and attach it to the root or another existing child node

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();
    }
}

The document element is the root element, which you need to set. Change line 27 to

document.appendChild(blobKey_E);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM