I am currently working on a xml project. So far, I have successfully link my xml to my java class using Dom Parser. I have the code provide below. What I am struggling with is updating my startdate's month by one so something like this 2/1/2013, 3/1/2013... will change in the xml file accordingly. I have the method call updateDate
at the bottom, but the xml file won't update it's value when I call it. Help will be appreciated
data.xml before
<?xml version="1.0" encoding="UTF-8">
<data>
<username>hello123</username>
<startdate>01/01/2011</startdate>
<enddate>06/01/2013</enddate>
</data>
desire data.xml after
<?xml version="1.0" encoding="UTF-8">
<data>
<username>hello123</username>
<startdate>02/01/2011</startdate> <--- This will change
<enddate>06/01/2013</enddate>
</data>
main.java
public class main {
public static void main(String[] args) {
Calendar cal2 = null;
String username = null;
String startdate = null;
String enddate = null;
String date = null;
String date_end = null;
try {
File data = new File("data.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(data);
doc.getDocumentElement().normalize();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
username = getValue("username", element);
startdate = getValue("startdate", element);
enddate = getValue("enddate", element);
}
}
date = startdate;
//end date
Date date_end = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(enddate);
Calendar end_date_cal = Calendar.getInstance();
end_date_cal.setTime(date_end);
// initial date
Date date_int = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(date);
cal2 = Calendar.getInstance();
cal2.setTime(date_int);
//call the method
updateDate(cal2);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("data.xml"));
transformer.transform(source, result);
System.out.println("Update Successfully");
}
} catch (Exception ex) {
log.error(ex.getMessage());
ex.printStackTrace();
}
}
private static void updateDate(Calendar cal2){
cal2.add(Calendar.MONTH, 1);
//need to push it back to the calendar
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
private static void setValue(String tag, Element element , String input) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
node.setTextContent(input);
}
}