javaxmldomxmlupdate

parsing XML tag with no data. getting NullPointerException


I have an xml with no data (for example the data for remark tag), so I try to update the contents of the remark tag, but I get a NullPointerException.

Here is teh sample code that I use.

NodeList itemCheckedNodeList = positionElement.getElementsByTagName("remark");
Element itemCheckedElement = (Element) itemCheckedNodeList.item(0);
NodeList itemCheckedLN = itemCheckedElement.getChildNodes();
Text itemCheckedText = (Text)itemCheckedLN.item(0);
itemCheckedText.setTextContent("Here is a new comment");

but I get a exception at "itemCheckedText.setTextContent(comments);"

<events>
      <event>
         <date>Some date here</date>
         <time>Some time here</time>
         <remark>Something about the event</remark>
      </event>
      <event>
         <date>Some date here</date>
         <time>Some time here</time>
         <remark></remark>
      </event>
</events>

Does anyone have the solution for this?


Solution

  • You'll need to add a null check for empty text nodes and create them as necessary:

    NodeList itemCheckedNodeList = positionElement.getElementsByTagName("remark");
    Element itemCheckedElement = (Element) itemCheckedNodeList.item(0);
    NodeList itemCheckedLN = itemCheckedElement.getChildNodes();
    Text itemCheckedText = (Text) itemCheckedLN.item(0);
    if (itemCheckedText == null) {
        Document doc = itemCheckedElement.getOwnerDocument();
        itemCheckedText = doc.createTextNode("remark");
        itemCheckedElement.appendChild(itemCheckedText);
    }
    itemCheckedText.setTextContent("Here is a new comment");