Java XML Element create new element with text value
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.Text; public class Main { public static void main(String args[]) { try {//from w w w. j a va2 s. c om DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse("data.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); Text txt = doc.createTextNode("What is DTD?"); Element e = doc.createElement("question"); e.appendChild(txt); e.setAttribute("id", "q3"); root.appendChild(e); transformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); } } }