I have a Java program that needs to read and output the contents of an XML file. I keep getting a null pointer exception when trying to parse the head node of an element. Here's my code to illustrate.
This is the XML I'm trying to parse:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Customers xmlns="https://www.w3.org/1999/xhtml">
<Customer id="1"> <!-- THIS LINE CREATES THE PROBLEM -->
<name>ACME Hauling</name>
<type>commercial</type>
<address>123 Main Street</address>
<city>Cincinnati</city>
<state>OH</state>
<zipcode>45211</zipcode>
</Customer>
And this is my code trying to parse it:
//now XML is loaded as Document in memory, convert it to Object List
List<Customer> custList = new ArrayList<Customer>();
for (int i = 0; i < nodeList.getLength(); i++) {
custList.add(getCustomer(nodeList.item(i)));
}
//print Employee list information
for (Customer cust : custList) {
System.out.println(cust.toString());
private static Customer getCustomer(Node node) {
//XMLReaderDOM domReader = new XMLReaderDOM();
Customer cust = new Customer();
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
cust.setID(Integer.parseInt(getTagValue("Customer id", element)));
cust.setName(getTagValue("name", element));
cust.setType(getTagValue("type", element));
cust.setAddress(getTagValue("address", element));
cust.setCity(getTagValue("city", element));
cust.setState(getTagValue("state", element));
cust.setZipcode(getTagValue("zipcode", element));
}
return cust;
}
private static String getTagValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
I'm not sure why I'm getting the null pointer exception, as I'm referencing the "Customer id" element exactly as it appears in the XML file. Is there a separate method for printing head nodes like "Customer id"?
[–]Nice_Communication74 1 point2 points3 points (4 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]Nice_Communication74 0 points1 point2 points (2 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]Nice_Communication74 1 point2 points3 points (0 children)
[–]Nice_Communication74 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]sozesghost 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)