XPath Select Attribute Values from Parent AND Child Nodes



Following is my XML File:



<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://ift.tt/1apoFAW" yahoo:lang="en-GB">
<results>

<sector sectorid="1" sectorname="Basic Materials">
<industry id="112" name="Agricultural Chemicals"/>
<industry id="132" name="Aluminum"/>
<industry id="110" name="Chemicals - Major Diversified"/>
<industry id="131" name="Copper"/>
<industry id="134" name="Gold"/>
<industry id="121" name="Independent Oil and Gas"/>
<industry id="120" name="Major Integrated Oil and Gas"/>
</sector>

</results>
</query>


From the above XML file, I am looking to store the values of attributes: sectorid, id, and name in the appropriate variables (I'm using Java). I have been looking at different XPath expressions and I came up with the following code, however, a java.lang.NumberFormatException: For input string: "" exception is thrown when storing the value of id attribute. Here's my code:



public class XMLToDatabase {

private static int __SectorID;
private static int __IndustryID;
private static String __IndustryName;

public static void main(String[] args) throws SQLException, UnsupportedEncodingException, ParserConfigurationException, SAXException, IOException, XPathExpressionException {

try {
File _XMLFile = new File("SectorsAndIndustries.xml");

DocumentBuilderFactory _DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
_DocumentBuilderFactory.setNamespaceAware(true);

DocumentBuilder _DocumentBuilder = _DocumentBuilderFactory.newDocumentBuilder();
Document _Document = _DocumentBuilder.parse(_XMLFile);

_Document.getDocumentElement().normalize();

XPath _XPath = XPathFactory.newInstance().newXPath();

XPathExpression _XPathExpression = _XPath.compile("//sector | //industry");

NodeList _NodeList = (NodeList) _XPathExpression.evaluate(_Document, XPathConstants.NODESET);


for (int i = 0; i < _NodeList.getLength(); i++) {
Node _Node = _NodeList.item(i);

if(_Node.getNodeType() == Node.ELEMENT_NODE) {
Element _Element = (Element) _Node;

__SectorID = Integer.parseInt(_Element.getAttribute("sectorid"));
__IndustryID = Integer.parseInt(_Element.getAttribute("id"));
__IndustryName = _Element.getAttribute("name");
}

System.out.println(__SectorID + ", " + __IndustryID + ", " + __IndustryName);
}
} catch (Exception e) {
e.printStackTrace();
}

}

}


Could someone please help me determine if it is the XPath Expression that I am making a mistake with, or if is the way I am storing the second variable __IndustryID? Because the first variable __SectorID correctly stores the value 1, but throws the above mentioned exception for __IndustryID. Ideally, I would want to store the values of all 3 attributes every time the for loop is executed, to save them to a database table. Please let me know if any more information is required.


No comments:

Post a Comment