tags:

views:

12

answers:

1

Hi,

I am trying to attach a node to a DOM document in the example code shown below. 1)I initialized the nodes "title, type" to null. 2)I tried to append these above nodes to the Document "child_doc" and then tried to set a new value to these nodes.

But on doing the above, I am getting a java.lang.NullPointerException at this line: child_doc.appendChild(title).setNodeValue("New" + childType);

How do I resolve this?

Thanks, Sony

Example code:

 public synchronized void attachNodeToParent1 (Element parent, String childType) throws ParserConfigurationException {
        Document parent_doc = parent.getOwnerDocument();

        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document child_doc = docBuilder.newDocument();

        Element child = null;
        Node title = null;
        Node type = null;        
        child_doc.appendChild(title).setTextContent("New" + childType);
        child_doc.appendChild(type).setTextContent(childType);

        child = child_doc.getDocumentElement();

        parent.appendChild(child);
    }
A: 

Initialize them to proper elements:

Element title = child_doc.createElement("type");
Element type = child_doc.createElement("title);
naikus
@sony This is why it is always good to have each line of code do one thing and one thing only.
Romain Hippeau