Как обновить значение узла в XML Java
В настоящее время я работаю над проектом XML. До сих пор я успешно связал свой XML с моим Java-классом, используя Dom Parser. У меня есть код, предоставленный ниже. Я борюсь с тем, чтобы обновить месяц моей начальной даты на один, чтобы что-то вроде этого 2/1/2013, 01.03.2013 ... соответственно изменилось в файле xml. У меня есть вызов методаupdateDate
внизу, но XML-файл не будет обновлять свое значение, когда я его вызываю. Помощь будет оценена
data.xmlдо
<?xml version="1.0" encoding="UTF-8">
<data>
<username>hello123</username>
<startdate>01/01/2011</startdate>
<enddate>06/01/2013</enddate>
</data>
желание data.xmlпосле
<?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);
}
}