简体   繁体   中英

getting null pointer exception when trying to parse a xml page by using dom

I wrote a parser for my xml page and I get a strange error that I totally didn't understand why. First I want to show you my xml page:

<?xml version="1.0" encoding="UTF-8"?>
<drugs xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://drugbank.ca" xs:schemaLocation="http://www.drugbank.ca/docs/drugbank.xsd" schemaVersion="1.4">
<drug type="biotech" created="2005-06-13 07:24:05 -0600" updated="2012-02-13 17:42:20 -0700" version="3.0">
<drugbank-id>DB00001</drugbank-id>
<name>Lepirudin</name>
<drug-interactions>
  <drug-interaction>
    <drug>DB01381</drug>
    <name>Ginkgo biloba</name>
    <description>Additive anticoagulant/antiplatelet effects may increase bleed risk. Concomitant therapy should be avoided.</description>
  </drug-interaction>
  <drug-interaction>
    <drug>DB00374</drug>
    <name>Treprostinil</name>
    <description>The prostacyclin analogue, Treprostinil, increases the risk of bleeding when combined with the anticoagulant, Lepirudin. Monitor for increased bleeding during concomitant thearpy. </description>
  </drug-interaction>
</drug-interactions>
<targets>
  <target partner="54">
    <actions>
      <action>inhibitor</action>
    </actions>
  </target>
</targets>
  </drug>
<partners>
<partner id="54">
  <name>Prothrombin</name>
  <general-function>Involved in blood clotting cascade</general-function>
</partner>
  </partners>

Here, you can see drug-interactions tag and inside of it there are information about interaction drugs. So when I remove drug-interactions tag, my parser works perfectly, but with drug-interaction tag, I'm getting NullPointerException.

Error Line:

if(nameElement.getChildNodes().item(0).getNodeValue().equals(str))

I'm putting whole code of parser here. You can try it yourself too. Why am I getting this error and how can I fix it? Sorry about long post. Thanks

import java.io.File;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class xmlParser {

public static void main(String argv[]) {
    getDrug("Lepirudin");
}


public static void getDrug(String str){
    ArrayList<String> arr = new ArrayList();
    String trgts = "";
    try {
        File file = new File("test.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        doc.getDocumentElement().normalize();
        System.out.println("Root element " + doc.getDocumentElement().getNodeName());

        NodeList drugList = doc.getElementsByTagName("drug");

        for (int s = 0; s < drugList.getLength(); s++) {

            Node drugNode = drugList.item(s);

            if (drugNode.getNodeType() == Node.ELEMENT_NODE) {

                Element drugElement = (Element) drugNode;

                Element nameElement = (Element) drugElement.getElementsByTagName("name").item(0);

                if(nameElement.getChildNodes().item(0).getNodeValue().equals(str)){
                    System.out.println("Name : " + nameElement.getChildNodes().item(0).getNodeValue());


                    Element drugNodeElement = (Element) drugElement.getElementsByTagName("drugbank-id").item(0);
                    System.out.println("ID : "  + drugNodeElement.getChildNodes().item(0).getNodeValue());

                    /////////////////////////////////////////////////
                    NodeList targetList = (NodeList) drugElement.getElementsByTagName("target");
                    for(int t=0; t<targetList.getLength(); t++)     
                    {
                        Node targetNode = targetList.item(t);
                        if(targetNode.getNodeType() == Node.ELEMENT_NODE)
                        {
                            Element targetElement = (Element) targetNode;


                            if(targetElement.getAttribute("position").equals(""))
                            {
                                System.out.println("target partner: " + targetElement.getAttribute("partner"));
                            }
                            else
                            {
                                System.out.println("target position: "+ targetElement.getAttribute("position")+ "target partner: "+ targetElement.getAttribute("partner"));

                            }
                            arr.add(targetElement.getAttribute("partner"));

                        }
                    }

                    System.out.println("-------------------------");

                }
            }

        }
        NodeList partnersList = doc.getElementsByTagName("partners");

        for (int q = 0; q < partnersList.getLength(); q++)
        {

            Node partnersNode = partnersList.item(q);
            if (partnersNode.getNodeType() == Node.ELEMENT_NODE) {
                Element partnersElement = (Element) partnersNode;
                NodeList partnerList = (NodeList) partnersElement.getElementsByTagName("partner");


                for(int w=0; w<partnerList.getLength(); w++)        
                {

                    Node partnerNode = partnerList.item(w);
                    if(partnerNode.getNodeType() == Node.ELEMENT_NODE)
                    {
                        Element partnerElement = (Element) partnerNode;

                        if(arr.contains(partnerElement.getAttribute("id"))){
                            Element partnernameElement = (Element) partnerElement.getElementsByTagName("name").item(0);
                            trgts += partnernameElement.getChildNodes().item(0).getNodeValue() + "," ;
                        }
                    }
                }
            }

        }

        trgts = trgts.substring(0, trgts.length()-1);
        System.out.println(trgts);

    } catch (Exception e) {
        e.printStackTrace();
    }
}


}

Null Pointer Exception means that you were trying to execute a function on a null pointer. What I suggest you do is to figure out how far along the note you got. Remove each of the function calls one at a time until you figure out how where the null is happening, and see if you can figure out why the value is returning null.

nameElement.getChildNodes().item(0).getNodeValue().equals(str)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM