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.
Element.getElementsByTagName("EmployeeRatesLevelA") where Element should be DataSet. Or you can use http://java.sun.com/javase/6/docs/api/org/w3c/dom/Node.html#getChildNodes()
then filter all the childs until you find the ones you want to.
I quite love groovy for these things, particularly if it's a one off to load stuff into a database:
http://groovy.codehaus.org/Reading+XML+using+Groovy%27s+XmlSlurper
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
As mentioned in the comments, please show us your Java code. You may also want to consider looking at JAXB - the Java Architecture for XML Binding. This is specifically geared towards representing XML as Java objects. It may not be feasible for your solution for whatever reason, but definitely take a look:
http://jaxb.java.net/tutorial/
DataSet
The following domain object below is what you described in your question:
Demo
The following code demonstrates how to use the JAXB runtime to convert your XML to/from your domain objects: