Home Tutorial Java Swing Java append new node to XML file


Share on Google+Share on Google+
Java append new node to XML file
Posted on: December 22, 2012 at 12:00 AM
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.


<?xml version="1.0" encoding="UTF-8" standalone="no"?>

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");
Element textNode1 = document.createElement("address");
Element nodeElement = document.createElement("student");
document.replaceChild(documentElement, documentElement);
Transformer tFormer =
tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
Source source = new DOMSource(document);
Result result = new StreamResult(xmlFile);
tFormer.transform(source, result);

} catch (Exception ex) {

Related Tags for Java append new node to XML file:

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 22, 2012

Recommend the tutorial

Advertisements Advertisements