Load XML and show data even if node not exist

You must Login before you can answer or comment on any questions.

I'm loading an external xml file on android. Now the problem is, the node photo is not always present. If that happens I get this error "java.lang.NullPointerException.

Is there any possibility to have/include a "check if null" of "if not exist" so I can load the xml file?

— asked 2 years ago by nada aver
1 Comment
  • Within code, its always possible to check for the existence of something. However, it makes it near impossible to give you an answer to your question without the proper info. In this case, a code example is most likely in high order as well as your dev specs. Please read the QA Checklist on the wiki and post back with the appropriate information.

    — commented 2 years ago by Anthony Decena

2 Answers

I'm guessing you are doing something like this to get your problem:

xml.documentElement.getElementsByTagName('photo').item(0).text
If so you could do this:
if (xml.documentElement.getElementsByTagName('photo') != null  && xml.documentElement.getElementsByTagName('photo').length > 0) {
//etc...
}

I use XPath to get my tags.

var ourNodeList = xml.evaluate('/parentNode/ourNode');
if (ourNodeList) {
   //We have a result, iterate it.
   var index = 0, maxNodes = ourNodeList.length;
   for (index =0; index < maxNodes; index++) {
      //Do something with ourNodes.item(index).
   }
}
If your search did not find any nodes, doesn't matter as your list length will be 0 and it won't iterate.

Your Answer

Think you can help? Login to answer this question!