4

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?

1
  • 1
    You're calling trim on a null value returned by getNodeValue. Check the result of that method before calling trim. Commented Sep 27, 2012 at 15:58

1 Answer 1

9

(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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.