Custom Search

Modifying / Editing XML Document in JAVA

Unlike PHP, C# or Asp.Net working with XML in Java is very big headache. I spend more than a day on Google searching for modifying an xml document in java. Finally i managed to get bits and pieces code snippets from various site and This article will guide you how we can modify the xml document in java, servlet and JSP.

This code snippets presented here does not uses third party XML Parser.




The structure of the XML document getting used here are:

< ?xml version="1.0" encoding="UTF-8"?>
     <connection>
	<number id="1"/>	
	<number id="2"/>	
     </connection>

XML Parser Package getting imported:

	import org.w3c.dom.*;
	import javax.xml.parsers.*; 
	import javax.xml.transform.*; 
	import javax.xml.transform.dom.DOMSource; 
	import javax.xml.transform.stream.StreamResult; 
	import org.xml.sax.SAXException;

Loading and Parsing XML Document:

	File file = new File("connections.xml");
 
	//Create instance of DocumentBuilderFactory
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 
	//Get the DocumentBuilder
	DocumentBuilder docBuilder = factory.newDocumentBuilder();
 
	//Parsing XML Document
	Document doc = docBuilder.parse(file);

Getting XML Root Element:

	Element root = doc.getDocumentElement();

Creating child Node:

	//Pointing to document root element
	Element root = doc.getDocumentElement();
 
	//create child element having tagName=number
	Element childElement = doc.createElement("number");
 
	//Adding number tag to root element
	root.appendChild(childElement);

Adding Attributes to an Element:

 
	//Pointing to document root element
	Element root = doc.getDocumentElement();
 
	//create child element having tagName=number
	Element childElement = doc.createElement("number");
 
	//Add the attribute to the child
	childElement.setAttribute("id","3");
 
	//Adding number tag havind id attribute to root element
	root.appendChild(childElement);

Saving the modified xml file:

    //setting up a transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
 
    //generating string from xml tree
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, result);
    String xmlString = sw.toString();
 
    //Saving the XML content to File
    OutputStream f0;
    byte buf[] = xmlString.getBytes();
    f0 = new FileOutputStream("connections.xml");
    for(int i=0;i<buf .length;i++) {
 	f0.write(buf[i]);
    }
	f0.close();
	buf = null;

Java Code for Modifying/Editing XML File:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.OutputStream;
import java.io.StringWriter;
import org.w3c.dom.*;
import javax.xml.parsers.*; 
import javax.xml.transform.*; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 
import org.xml.sax.SAXException;
 
public class modifyXML {
   public static void main(String args[]) {
     try {	
	File file = new File("connections.xml");
 
	//Create instance of DocumentBuilderFactory
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 
	//Get the DocumentBuilder
	DocumentBuilder docBuilder = factory.newDocumentBuilder();
 
	//Using existing XML Document
	Document doc = docBuilder.parse(file);
 
	//create the root element
	Element root = doc.getDocumentElement();
 
	//create child element
	Element childElement = doc.createElement("number");
 
        //Add the attribute to the child
	childElement.setAttribute("id","3");
	root.appendChild(childElement);
 
	//set up a transformer
	TransformerFactory transfac = TransformerFactory.newInstance();
	Transformer trans = transfac.newTransformer();
 
        //create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        String xmlString = sw.toString();
 
        OutputStream f0;
	byte buf[] = xmlString.getBytes();
	f0 = new FileOutputStream("connections.xml");
	for(int i=0;i<buf .length;i++) {
	   f0.write(buf[i]);
	}
	f0.close();
	buf = null;
     }
     catch(SAXException e) {
	e.printStackTrace();		
     }
     catch(IOException e) {
        e.printStackTrace();		
     }
     catch(ParserConfigurationException e) {
       e.printStackTrace();		
     }
     catch(TransformerConfigurationException e) {
       e.printStackTrace();		
     }
     catch(TransformerException e) {
       e.printStackTrace();		
     }
  }
}

Related Post

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)