首先加载XML文件…
documentBuilderFactory f = documentBuilderFactory.newInstance();documentBuilder b = f.newdocumentBuilder();document doc = b.parse(new File("Data.xml"));现在,有几种方法可以执行此操作,但简单来说,您可以使用xpath API查找所需的节点并更新其内容
XPath xPath = XPathFactory.newInstance().newXPath();Node startDateNode = (Node) xPath.compile("/data/startdate").evaluate(doc, XPathConstants.NODE);startDateNode.setTextContent("29/07/2015");xPath = XPathFactory.newInstance().newXPath();Node endDateNode = (Node) xPath.compile("/data/enddate").evaluate(doc, XPathConstants.NODE);endDateNode.setTextContent("29/07/2015");然后保存
document回文件…
Transformer tf = TransformerFactory.newInstance().newTransformer();tf.setOutputProperty(OutputKeys.INDENT, "yes");tf.setOutputProperty(OutputKeys.METHOD, "xml");tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");DOMSource domSource = new DOMSource(doc);StreamResult sr = new StreamResult(new File("Data.xml"));tf.transform(domSource, sr);


