Java tutorial
//package com.java2s; import java.io.File; import java.io.FileOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; 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.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class Main { public static void saveOrUpdate(String nodeName, String value) { try { updateNode(nodeName, value); } catch (NullPointerException e) { insertNode(nodeName, value); } catch (Exception e) { e.printStackTrace(); } } private static void updateNode(String nodeName, String value) throws Exception { File f = new File(System.getProperty("user.dir") + "\\DBConf.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(f); Node tempElem = doc.getElementsByTagName(nodeName).item(0); tempElem.getFirstChild().setNodeValue(value); doc.getElementsByTagName("conf").item(0).appendChild(tempElem); DOMSource source = new DOMSource(doc); StreamResult res = new StreamResult(new FileOutputStream(f)); TransformerFactory.newInstance().newTransformer().transform(source, res); } private static void insertNode(String nodeName, String nodeValue) { File f = new File(System.getProperty("user.dir") + "\\DBConf.xml"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document doc = builder.parse(f); Element tempElem = doc.createElement(nodeName); Text child = doc.createTextNode(nodeValue); tempElem.appendChild(child); doc.getElementsByTagName("conf").item(0).appendChild(tempElem); DOMSource source = new DOMSource(doc); StreamResult Streamres = new StreamResult(new FileOutputStream(f)); TransformerFactory.newInstance().newTransformer().transform(source, Streamres); } catch (Exception e) { e.printStackTrace(); } } }