Modify XML and save in Java using DOM API


This post is for beginners who wish to modify XML file content using DOM API and save it back into the XML file. This post just outlines the steps involved in the process and does not cover complex manipulation of the XML.

In the below XML, we will modify the value of name under the root element project.

<?xml version="1.0" encoding="UTF-8"?>
<project>
<name>abcd</name>
</project>

Below is the Java code which will change the value of abcd to "newproject_name" and persist the changes in the XML file located at "e:\\temp\\sample.xml"

package com.ts.sample;

import java.io.File;
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.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author karthikeyanc
 */
public class Main {

    public static void main(String[] args) throws Exception {
        String xmlFilePath = "e:\\temp\\sample.xml";

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(xmlFilePath);

        replaceValue(doc, "name", "newproject_name");

        Transformer t = TransformerFactory.newInstance().newTransformer();
        Result result = new StreamResult(new File(xmlFilePath));
        Source source = new DOMSource(doc);
        t.transform(source, result);


    }

    private static void replaceValue(Document doc, String tagName, String replaceValue) {
        NodeList nodeList = doc.getElementsByTagName(tagName);
        Node node = nodeList.item(0);
        node.getFirstChild().setNodeValue(replaceValue);
    }
}

 

 
 
 
 
Comments:

Thanks a lot, this is a good start!

Posted by Superman on October 01, 2008 at 08:19 AM CDT #

Thanks a lot !! This saved my time. I am not a beginner but was not aware of converting DOM tree into another format. I am converting it to the String which is needed for the use case I am implementing.

Sharing the code herewith so that anyone else like me would benefit.

**********Start****************
Transformer t = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(new StringWriter());
//documentChanged is the Document object you modified in memory.
t.transform(new DOMSource(documentChanged),result);
//Way to get back the string buffer that was written
StringBuffer buff = ((StringWriter)result.getWriter()).getBuffer();
System.out.println("modified xml -- " + buff);
**********End****************

Posted by Amit on October 22, 2008 at 02:02 PM CDT #

Post a Comment:
  • HTML Syntax: Allowed
 

« January 2009
SunMonTueWedThuFriSat
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
       
Today

Valid XHTML or CSS?

[This is a Roller site]
 
© Karthik