XML parsing using DOM parser java
I'm finding problem in parsing the xml file using the DOM parser. Where my problem is i have a parent tag called employee, where it's children node are having the same name but different attribute value. So when i run the below code it leads to the following error. Could Anyone please help me.
ERROR:
java.lang.NullPointerException
at XMLParser.getValue(XMLParser.java:53)
at XMLParser.main(XMLParser.java:30)
ERROR:
java.lang.NullPointerException
at XMLParser.getValue(XMLParser.java:53)
at XMLParser.main(XMLParser.java:30)
// this is my xml file named sample.xml <?xml version="1.0" encoding="UTF-8"?> <result> <Employee> <row no="1"> <FL val="ID"> <![CDATA[22844]]> </FL> <FL val="Name"> <![CDATA[SureshKumar]]> </FL> <FL val="Gender"> <![CDATA[Male]]> </FL> </row> <row no="2"> <FL val="ID"> <![CDATA[22845]]> </FL> <FL val="Name"> <![CDATA[Nikumbh]]> </FL> <FL val="Gender"> <![CDATA[Male]]> </FL> </row> </Employee> </result>
// this is XMLParser.java used to parse the Sample.xml file
import java.io.File;
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 args[]) {
try {
File employee = new File("Sample.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(employee);
doc.getDocumentElement().normalize();
System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName("row");
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("ID: " + getValue("ID", element));
System.out.println("Name: " + getValue("Name", element));
System.out.println("Gender: " + getValue("Gender", element));
S
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private static String getValue(String tag, Element element)
{
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
0