Access Parent and child node
I am trying to retrieve attributes for the parent and child nodes. When running the below code I am only getting one line while the XML file has several lines. Can someone point me what I am doing wrong here:
Here is the out put I am getting when running the below code against my xml file:
57511:2011-03-12:2011-03-18:1170108:2011-03-12 1218:2011-03-12 1248
Here is part of the xml file:
<Ed CreationSource="Bluecube" CreationTimestamp="2011-03-23 13:57:01" >
<Unit name="57511" startDate="2011-03-12" endDate="2011-03-18">
<Shift employeeID="1170108" start="2011-03-12 0718" end="2011-03-12 1636" >
<Detail type="Meal" start="2011-03-12 1218" end="2011-03-12 1248" />
</Shift>
<Shift employeeID="1170108" start="2011-03-13 2248" end="2011-03-14 0724" />
<Shift employeeID="1170108" start="2011-03-14 2300" end="2011-03-15 0724"/>
<Shift employeeID="1290534" start="2011-03-12 0700" end="2011-03-12 1306"">
<Detail type="Meal" start="2011-03-12 1200" end="2011-03-12 1230" />
</Shift>
<Shift employeeID="1290534" start="2011-03-13 0600" end="2011-03-13 1200" />
<Shift employeeID="1290534" start="2011-03-15 0530" end="2011-03-15 1248">
<Detail type="Meal" start="2011-03-15 1124" end="2011-03-15 1212" />
</Shift>
</Unit>
</Ed>
Here is my code that attempts to read the above XML file:
Code:
static class Entry {
final String BusinessUnit,EmpId,ShiftStart, ShiftEnd, MealStart,MealEnd;
Entry(String BusinessUnit, String EmpId,String ShiftStart,String ShiftEnd, String MealStart,String MealEnd) {
//this.EnterpriseDocument = EnterpriseDocument;
this.BusinessUnit = BusinessUnit;
this.EmpId = EmpId;
this.ShiftStart = ShiftStart;
this.ShiftEnd = ShiftEnd;
this.MealStart = MealStart;
this.MealEnd = MealEnd;
}
@Override public String toString() {
return String.format("%s:%s:%s:%s:%s:%s",BusinessUnit,EmpId, ShiftStart, ShiftEnd, MealStart,MealEnd);
}
}
final static XPath xpath = XPathFactory.newInstance().newXPath();
static String evalString(Node context, String path) throws XPathExpressionException {
return (String) xpath.evaluate(path, context, XPathConstants.STRING);
}
public static void main(String[] args) throws Exception {
File file = new File("C:/PunchExport.xml");
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
NodeList entriesNodeList = (NodeList) xpath.evaluate("//BU", document, XPathConstants.NODESET);
List<Entry> entries = new ArrayList<Entry>();
for (int i = 0;
i < entriesNodeList.getLength();
i++) {
Node entryNode = entriesNodeList.item(i);
// System.out.println(entryNode);
entries.add(new Entry(
evalString(entryNode, "@name"),
evalString(entryNode, "@startDate"),
evalString(entryNode, "@endDate"),
evalString(entryNode, "Shift//@employeeID"),
evalString(entryNode, "Shift//Detail//@start"),
evalString(entryNode, "Shift//Detail//@end")
));
//System.out.println(entries);
for (Entry entry : entries) {
System.out.println(entry);
}
}
}}