Creating XML Element and add to Document
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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;
public class Main {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
Document newDoc = domBuilder.newDocument();
Element rootElement = newDoc.createElement("parent");
newDoc.appendChild(rootElement);
Element rowElement = newDoc.createElement("row");
Element curElement = newDoc.createElement("newValue");
curElement.appendChild(newDoc.createTextNode("newText"));
rowElement.appendChild(curElement);
rootElement.appendChild(rowElement);
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource(newDoc);
Result dest = new StreamResult(new File("xmlFileName.xml"));
aTransformer.transform(src, dest);
}
}
Output:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<parent><row><newValue>newText</newValue></row></parent>