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?
(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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With