如何在java中更新xml文件 [英] How to update xml files in java
问题描述
我有一个xml文件调用data.xml,如下面的代码。项目可以从客户端运行没问题,它可以读取xml文件。我现在遇到的问题是我想编写一个可以更新startdate和enddate的函数。我不知道如何开始。我们将不胜感激。
I have a xml file call data.xml like the code below. The project can run from client side no problem and it can read the xml file. The problem I have now is I I want to write a function that can update the startdate and enddate. I have no idea how to get start. Help will be appreciated.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<data>
<username>admin</username>
<password>12345</password>
<interval>1</interval>
<timeout>90</timeout>
<startdate>01/01/2013</startdate>
<enddate>06/01/2013</enddate>
<ttime>1110</ttime>
</data>
my main.java
my main.java
public class main
{
public static void main(String[] args)
{
Calendar cal2 =null;
try {
//read the xml
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;
Date date_int = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(date);
cal2 = Calendar.getInstance();
cal2.setTime(date_int);
//loop the child node to update the initial date
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
setValue("startdate", element , date_int.toString());
}
}
//write the content in xml file
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);
} catch (Exception ex) {
log.error(ex.getMessage());
ex.printStackTrace();
}
}
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);
}
推荐答案
首先出现您的XML中存在错误,您有额外的< data>
标记。我删除了它。现在您有两个选项可以使用 SAX
或 DOM
。我建议 DOM
原因是你可以使用 DOM
读取完整的XML,并且对于像这样的一小段XML来说更好的选择。
Firstly there is an error in your XML you have extra <data>
tag . I have removed it. Now you have two options you could either use SAX
or DOM
. I would suggest DOM
reason being that you can read full XML using DOM
and for a small piece of XML like this it's better choice.
代码
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class ModifyXMLFile {
public static void main(String argv[]) {
try {
String filepath = "file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get the root element
Node data= doc.getFirstChild();
Node startdate = doc.getElementsByTagName("startdate").item(0);
// I am not doing any thing with it just for showing you
String currentStartdate = startdate.getNodeValue();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date today = Calendar.getInstance().getTime();
startdate.setTextContent(df.format(today));
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println("Done");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
更正的XML
<?xml version="1.0" encoding="UTF-8"?>
<data>
<username>admin</username>
<password>12345</password>
<interval>1</interval>
<timeout>90</timeout>
<startdate>29/07/2015</startdate>
<enddate>06/01/2013</enddate>
<ttime>1110</ttime>
</data>
这篇关于如何在java中更新xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!