Java tutorial
//package com.java2s; //License from project: Apache License import java.io.FileInputStream; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; 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.NodeList; public class Main { public static void addApp(String file, String name, Hashtable<String, String> attri) throws Exception { DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance(); DocumentBuilder dombuilder = domfac.newDocumentBuilder(); FileInputStream is = new FileInputStream(file); Document doc = dombuilder.parse(is); NodeList nodeList = doc.getElementsByTagName("app"); if (nodeList != null && nodeList.getLength() >= 1) { Node deviceNode = nodeList.item(0); Element device = doc.createElement("aut"); device.setTextContent(name); for (Iterator itrName = attri.keySet().iterator(); itrName.hasNext();) { String attriKey = (String) itrName.next(); String attriValue = (String) attri.get(attriKey); device.setAttribute(attriKey, attriValue); } deviceNode.appendChild(device); } //save TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); Properties props = t.getOutputProperties(); props.setProperty(OutputKeys.ENCODING, "GB2312"); t.setOutputProperties(props); DOMSource dom = new DOMSource(doc); StreamResult sr = new StreamResult(file); t.transform(dom, sr); } }