java - avoid null pointer excpetion while parsing the xml -


this xml parse

<metadata>     <groupid>org.chromium</groupid>     <artifactid>chromedriver-win32</artifactid>     <versioning>         <release>2.14</release>         <versions>             <version>2.14</version>         </versions>         <lastupdated>20150610112540</lastupdated>     </versioning> </metadata> 

while trying parse above xml, getting nullpointerexception though have handled null check. below code

private string getversionfromnode(element eelement) {     string version = null;      // latest version     string tagname = "latest";     try {         version = eelement.getelementsbytagname(tagname).item(0).gettextcontent();         // if latest version not available take release         // version         if ( version.isempty() ||  null == version || "null" == version) {             tagname = "release";             version = eelement.getelementsbytagname(tagname).item(0).gettextcontent();         }     }     catch (nullpointerexception e) {        system.out.println("not able parse " + tagname + " tag " + e.getmessage());     }      return version; } 

when version null, should enter in below block.

if ( version.isempty() ||  null == version || "null" == version) {     tagname = "release";     version = eelement.getelementsbytagname(tagname).item(0).gettextcontent();  } 

what should solution problem?

your string tagname "latest" , in xml file, there no element named latest , version remains null , therefore nullpointerexception generated when code:

version.isempty()   

is executed in if statement. because version null. , code tries check if null empty. cannot. , so, nullpointerexception generated here.

to handle situation, first check if version null. secondly check if string version equal string "null". , thirdly check if empty. change sequence of conditions in if statement from:

if ( version.isempty() ||  null == version || "null" == version)   

to

if (null == version || "null" == version || version.isempty())   

by way, side tip, use:

"null".equals(version)   

rather

"null" == version 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -