Java append new node to XML file


 

Java append new node to XML file

In this tutorial, you will learn how to append new node to xml file.

In this tutorial, you will learn how to append new node to xml file.

Java append new node to XML file

In this tutorial, you will learn how to append new node to xml file. Sometimes there is a need to append a new XML node to the xml file. Here is an xml file where we are going to append a new node.

file.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<school>
<student>
<name>Angelina</name>
<address>Delhi</address>
</student>
<student>
<name>Martina</name>
<address>Mumbai</address>
</student>
</school>

Here is a code that appends a new node student with name and address elements.

import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class AppendNode {

public static void main(String[] args) {
try {
File xmlFile = new File("C:\\file.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(xmlFile);
Element documentElement = document.getDocumentElement();
Element textNode = document.createElement("name");
textNode.setTextContent("Rose");
Element textNode1 = document.createElement("address");
textNode1.setTextContent("Delhi");
Element nodeElement = document.createElement("student");
nodeElement.appendChild(textNode);
nodeElement.appendChild(textNode1);
documentElement.appendChild(nodeElement);
document.replaceChild(documentElement, documentElement);
Transformer tFormer =
TransformerFactory.newInstance().newTransformer();
tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
Source source = new DOMSource(document);
Result result = new StreamResult(xmlFile);
tFormer.transform(source, result);


} catch (Exception ex) {
System.out.println(ex);
}
}
}

Ads