javaxmlnullpointerexceptionmarc

Dealing with non existing nodes in XML Java


I have to process a variety of XML files in MARC format. The files contain different fields and sometimes fields may be missing. In this particular case the author's field does not exist, and it should be saved as an empty string.

How can I check if a node exists before trying to access its value?

If I try to access the non existing node, the program throws a NullPointerException.

// xml document is valid and existing nodes can be accessed without a problem
final Document doc = record.getDocument(); 
String author = "";
if (doc != null) {
    // The next line throws a NullPointerException
    author = doc.selectSingleNode("//mx:datafield[@tag='100']/mx:subfield[@code='a']").getText();
}

I have tried creating a list with the nodes, and then checking if it is not empty. However, even if the field does not exist in the xml file, the list of nodes still contains one element.

String xpath = "//mx:datafield[@tag='100']/mx:subfield[@code='a']";
List<Node> nodes = doc.selectNodes(xpath); //contains one element

Solution

  • The problem is that you check the existance of the doc (doc!=null), but not the existance of the Node. Check it like this, for example:

    final Document doc = record.getDocument(); 
    String author = "";
    
    if (doc != null)
    {   
        Node node = doc.selectSingleNode("//mx:datafield[@tag='100']/mx:subfield[@code='a']")
        if (node!=null)
          author = node.getText();
    }
    

    p.s: I don't know the nature of Node, I just put it like pseudocode.