import javax.xml.parsers.*; import org.w3c.dom.*; import java.util.*; import java.io.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import javax.xml.transform.dom.*; public class AddRecord2 { public static void main(String[] args) { //System.out.println("Hello World!"); String name="fancy"; DocumentBuilder parser; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { parser = factory.newDocumentBuilder(); Document doc = parser.parse("user.xml"); Element newlink=doc.createElement(name); doc.getDocumentElement().appendChild(newlink); outputDoc(doc); } catch (Exception e) { //to do it } } public static void outputDoc (Document doc) { DOMSource doms = new DOMSource (doc); //Input. Document is an extended class of Node, and therefore //can be used here. File f = new File ("xuser2.xml"); StreamResult sr = new StreamResult (f); // Output. try { TransformerFactory tf=TransformerFactory.newInstance(); // Get a TransformerFactory. Transformer t=tf.newTransformer (); // Make a new Transformer from it //Properties properties = t.getOutputProperties(); //properties.setProperty(OutputKeys.ENCODING,"GB2312"); //t.setOutputProperties(properties); // now proceed with the transformation t.transform(doms,sr); // Use the DOMSource as input. StreamResult as output path. } catch (TransformerConfigurationException tce) { System.out.println("Transformer Configuration Exception\n-----"); tce.printStackTrace(); } catch (TransformerException te) { System.out.println ("Transformer Exception\n---------"); te.printStackTrace (); } } }