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 ofNode firstby doingSystem.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, onlyNode.ELEMENT_NODEwill have non-null forgetAttributes():