简体   繁体   中英

Null pointer exception when reading xml file

I have a class named xmlReader that have parse(String path) and parseXml(Document doc) methods. I define:

    xmlReader reader = new xmlReader();
    Document doc =   reader.parse(PATH);
    reader.parseXml(doc);`

My parseXml method:

public void parseXml(Document doc)
{
    Node first = doc.getFirstChild().getFirstChild();
    NamedNodeMap att = first.getAttributes();
    Node id = att.item(0);
    NodeList l = first.getChildNodes();
    System.out.println("id:" + id.getNodeValue());
    for(int i = 0; i < l.getLength(); i++)
    {
        Node temp = l.item(i);
        System.out.println(temp.getNodeName() + ": " +
                temp.getNodeValue());
    }

}

The problem: line 3 of parseXml method:

When Node id = att.item(0) the program get a null ref exception. When debugging I see that the doc is defined null . Why is that? Its like its not reading the file correctly.

Thanks?

This is my parse(String path) method:

public Document parse(String path) 
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;

try 
{
    db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Document doc = null;
try 
{
    doc = db.parse(path);
} catch (SAXException e) {

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

    e.printStackTrace();
}
return doc;
}

Take a look at http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html#getAttributes ()

Before you do this Node id = att.item(0); take a look at the object type of Node first by doing System.out.println(first); your probably going to see that this is a text element and not an element.

What you've done when you said Node first = doc.getFirstChild().getFirstChild(); is "give me the first child of the first element, which is probably a text element. What you should be doing is checking for ELEMENT nodes like this, only Node.ELEMENT_NODE will have non-null for getAttributes() :

        NodeList nl = doc.getFirstChild().getChildNodes();
        for (int i = 0; i < nl.getLength(); i++){
            Node first = nl.item(i);
            if (first.getNodeType() == Node.ELEMENT_NODE){
                System.out.println("first:" + first);
                NamedNodeMap att = first.getAttributes();
                System.out.println("att:" + att);
            }

        }

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