0

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?

Sana
  • 9,895
  • 15
  • 59
  • 87

2 Answers2

2

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");
WhiteFang34
  • 70,765
  • 18
  • 106
  • 111
  • But there is already a remark node, so if I create it, then is it not going to be redundant? I mean adding the same tag again! – Sana Apr 06 '11 at 03:59
  • 1
    The element node is there but it has no child text node. It gives you a null instead of an empty text node. You just have to fill that in. I verified it works if that helps :) – WhiteFang34 Apr 06 '11 at 04:03
1

Text between elements are represented as node children. An empty element probably do not have a text node child, so you have to

  1. get the remark
  2. check if there is a text node child, if not create it
  3. set the text
ThomasRS
  • 8,215
  • 5
  • 33
  • 48