Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for an empty XML element in JAVA

I have an XML as follows:

<info>
    <userId>Admin</userId>
    <userNotes></userNotes>         
</info>

I am trying to parse this in JAVA. and here is my code snippet:

NodeList userIdNodeList = document.getElementsByTagName("userId");

if (userIdNodeList!=null) {
    userId = userIdNodeList.item(0).getChildNodes().item(0).getNodeValue().trim();
}            

NodeList userNotesNodeList = document.getElementsByTagName("userNotes");

if (userNotesNodeList!=null) {
    userNotes = userNotesNodeList.item(0).getChildNodes().item(0).getNodeValue().trim();
}            

But the above code is throwing a NULL pointer error because the userNotes element is empty.

Any ideas on how to fix this?

like image 213
ridermule Avatar asked Oct 20 '25 05:10

ridermule


1 Answers

(Corrected)

userNotesNodeList.item(0).getChildNodes().getLength() will return 0 if there are no child elements nor text.

Why

userNotesNodeList is the list of <userNotes> nodes. There are 1. Anyway you could check the length to verify it.

userNotesNodeList.item(0) is the first <userNotes> element.

userNotesNodeList.item(0).getChildNodes() is the list of things that are inside <userNotes>...</userNotes>.

In case of no text this is a NodeList with 0 elements so

userNotesNodeList.item(0).getChildNodes().getLength() should return 0.

I suggest using vars for intermidiate results (to make a clearer code). Or creating some helper methods to avoid this cumbersome XML api.

NodeList userNotesNodeList = document.getElementsByTagName("userNotes");
// userNotesNodeList should not be null, it can be zero length, but not null
Element userNotesElement = (Element) userNotesNodeList.item(0);
if (userNotesElement.getChildNodes().getLength() > 0) // then it has text
{
   userNotes = userNotesElement.getChildNodes().item(0).getNodeValue();
}
like image 192
helios Avatar answered Oct 22 '25 19:10

helios