Share on Google+Share on Google+

Java XML modification

Ads
This section explain you how to modify the xml file using DOM parser.

Java XML modification

This section explain you how to modify the xml file using DOM parser. For this purpose, you have to use DocumentBuilderFactory, DocumentBuilder and Document classes to get the default DOM parser and parse the xml file. Then call the function delNode() that finds the specified node from the node list and remove it along with its value. 
The object of Document type is then passed in the DOMSource() constructor. Create a StreamResult  object to generate the result. The transform() method of Transformer class takes the Source and StreamResult objects and it processes the source tree to the output .

Here is the data.xml:

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

<Person>
<FirstName>Angelina</FirstName>
<
LastName>Jolie</LastName>
<Address>Delhi</Address>
<ContactNo>111111</ContactNo>

<FirstName>Julia</FirstName>
<
LastName>Roberts</LastName>
<
Address>Mumbai</Address>
<
ContactNo>222222</ContactNo>

<
/Person>

Here is the code:

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

public class Delete {
	static Transformer tFormer;
	static DocumentBuilder builder;
	static Document document;

	public static void main(String[] args) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		TransformerFactory tFactory = TransformerFactory.newInstance();
		try {
			tFormer = tFactory.newTransformer();
			builder = factory.newDocumentBuilder();
			document = builder.parse(new File("data.xml"));
			delNode(document, "ContactNo");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void delNode(Node parent, String filter) {
		try {
			NodeList children = parent.getChildNodes();

			for (int i = 0; i < children.getLength(); i++) {
				Node child = children.item(i);

				if (child.getNodeType() == Node.ELEMENT_NODE) {

					if (child.getNodeName().equals(filter)) {
						parent.removeChild(child);
					} else {
						delNode(child, filter);
					}
				}
			}
			Source source = new DOMSource(document);
			StreamResult dest = new StreamResult("data.xml");
			tFormer.transform(source, dest);
		} catch (Exception e) {
		}
	}

}

Advertisements

Posted on: April 26, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.

Ads

Advertisement