I am trying to parse the following xml. I can access the WeekNumber easily but cannot access the children for EmployeeRatesLevelA and EmployeeRatesLevelB. The goal is to save these to a class, DataSet with fields WeekNumber and ArrayLists, EmployeeRatesLevelA and EmployeeRatesLevelB.
Thanks.
<DataSet ActiveFrom="2011/04/06">
<WeekNumber>8</WeekNumber>
<EmployeeRatesLevelA>
<Rate>0</Rate>
<Rate>0.12</Rate>
</EmployeeRatesLevelA>
<EmployeeRatesLevelB>
<Rate>0.15</Rate>
<Rate>0.20</Rate>
</EmployeeRatesLevelB>
</DataSet>
Document doc = loadXml("data.xml");
NodeList nodeList = doc.getElementsByTagName("DataSet");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
NodeList weekNumberList = element.getElementsByTagName("WeekNumber");
Element weekElement = (Element) weekNumberList.item(0);
NodeList textElementList = weekElement.getChildNodes();
System.out.println("Weeknumber:"+ ((Node)textElementList.item(0)).getNodeValue().trim());
}
public static Document loadXml(String file) {
try {
return (DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(file)));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return null;
}
This gives me the Weeknumber but I am unable to access EmployeeRatesLevelA and EmployeeRatesLevelB.
Would like to learn other cool stuff but as I am new to Java and the xml document is really small, DOM should suffice.
If you want to use DOM, I suggest you to start by writing some helper classes to make your work easier. Here is one I written recently for my personal use.
Let’s start with the helper classes in package xml.utils
XmlException.java
XmlDocument.java
XmlNode.java
Now the DataSet.java and Main.java are as follows:
DataSet.java
Main.java