Java XML Element append child
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; 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; import org.w3c.dom.Text; public class Main { public static void main(String args[]) { try {// w w w .j ava2s . c o m DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse("questions.xml"); Element root = doc.getDocumentElement(); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(root); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); NodeList questions = doc.getElementsByTagName("question"); Node aCopy = questions.item(0).cloneNode(true); ((Element) aCopy).setAttribute("id", "q3"); ((Text) aCopy.getFirstChild()).replaceWholeText("What is XML?"); root.appendChild(aCopy); transformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); } } }