Sunday, 2 November 2014

DOM - Missing Element in XML Document



The XML file contains Employee (with empID, empName, empCode). In some situation empCode is missing.



<Employee><Detail><empID>1</empID><empName>Abhi</empName><empCode>One</empCode>
</Detail>

<Detail><empID>2</empID><empName>Amit</empName>
</Detail>
</Employee>


I am getting the Null pointer Exception while calling the getTagValue() method for "empCode" as there is no tag available with the name in XML.


Java Code :


try { File xmlFile = new File("New.xml");



DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("Detail");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
EmpDetail empInfo = new EmpDetail();

empInfo.SetEmpID(getTagValue("empID", eElement));
empInfo.SetEmpName(getTagValue("empName",eElement));
empInfo.SetEmpCode(getTagValue("empCode",eElement));

DBConnector.SaveinDB(empInfo);
}

}
}
catch (Exception e)
{
System.out.println("Error: ");
e.printStackTrace();
}
}

private static String getTagValue(String sTag, Element eElement)
{
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
if(nValue == null)
return null;
return insertEscapeSequance(nValue.getNodeValue());
}

private static String insertEscapeSequance(String str)
{
String returnstr = "";
String[] strarr = str.split("'");
returnstr = strarr[0];
for(int i=1;i<strarr.length;i++)
{
returnstr = returnstr + "\\'" + strarr[i];
}
return returnstr;
}


Now I want to save the XML data into sql like this :


1 Abhi One 2 Amit null


I tried so many links but not success. Can someone please help me


No comments:

Post a Comment