Reputation: 433
I have entered below code to file, but it throws NullPointerException
. I am trying to parse resource.xml file using DOM parser. The first item is printed successfully, but it stucks in the second iteration.
package readXmlProject;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class readXml {
public static void main(String[] args){
try{
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("resource.xml");
doc.getDocumentElement().normalize();
NodeList fieldsList = doc.getElementsByTagName("records").item(0).getChildNodes();
System.out.println(fieldsList.getLength());
for (int i = 0; i < fieldsList.getLength(); i++) {
NodeList itemDetails = fieldsList.item(i).getChildNodes();
for(int j=0;j<fieldsList.getLength();j++){
System.out.println(itemDetails.item(j).getTextContent());
}
}
}
catch(Exception e){
e.printStackTrace();
};
}
public static void getFieldsList(Document doc){
NodeList fieldsList = doc.getElementsByTagName("fields").item(0).getChildNodes();
for (int i = 0; i < fieldsList.getLength(); i++) {
System.out.println(fieldsList.item(i).getNodeName());
}
}
}
After executing the above code below is the output :
100
1
1438929000
'00851'
BNC SUVIDHA SPL
1
BBS
BHUBANESWAR
'00:00:00'
'22:50:00'
0
BBS
BHUBANESWAR
BNC
BANGALORE CANT
java.lang.NullPointerException
at readXmlProject.readXml.main(readXml.java:22)
According to above error, below line is causing the error
System.out.println(itemDetails.item(j).getTextContent());
Upvotes: 0
Views: 250
Reputation: 196
It appears that you want to iterate over the items in the itemDetails list in the inner loop. If so, the code for the inner loop should be
for(int j=0;j<itemDetails.getLength();j++){
Upvotes: 0
Reputation: 2523
I suspect you need to change the inner loop.
for(int j=0;j<fieldsList.item(i).getLength();j++){
Upvotes: 0
Reputation: 11022
for(int j=0;j<fieldsList.getLength();j++)
should be for(int j=0;j< itemDetails.getLength();j++)
Upvotes: 1