开发者

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?


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");


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜