2

I am parsing XML datas, but when in XML is tag without text (only <item/> ) it writes error:

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String org.w3c.dom.Node.getNodeValue()' on a null object reference

This is function where I get error:

private static String getNode(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
            .getChildNodes();
    Node nValue = (Node) nlList.item(0);
    return nValue.getNodeValue(); //here I get error
}

Can somebody help me with this problem? Thank you very much.

2
  • Check on null if it is not null return value if it is null return something else for example an empty String Commented Feb 2, 2018 at 21:28
  • Just because nlList.item(0) existed, doesn't mean it's not null Commented Feb 2, 2018 at 21:29

1 Answer 1

4

This problem occurs because that nValue is null. You need to decide how your method should act in this situation and use this code

if(nValue!=null)
{
    return nValue.getNodeValue();
}
else
{
    //the tag has no value
    //return other default value or maybe throw your own exception 
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's my pleasure!

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.