javawaveblogs-20

Monday, October 8, 2007

DOM parsing technique

This class follows the DOM parsing technique and does the following.

1.Parse the demoxml.xml file.
2.Search for the xml node by the name "parent1" from the xml.
3.Create a new child node by the name "newChild"
4.Create a text("new child of the parent1") to the "newChild" node
5.Append the "newChild" node to "parent1" node.
6.Save the changes (transform) to the xml.


Sample Code: (
DOMParser.java)
package com.dom.dhanago;

/*
* This class follows the DOM parsing technique and does the following.
* 1.Parse the demoxml.xml file. 2.Search for the xml node by the name
* "parent1" from the xml. 3.Create a new child node by the name "newChild"
* 4.Create a text("new child of the parent1") to the "newChild" node
* 5.Append the "newChild" node to "parent1" node. 6.Save the changes
* (transform) to the xml.
*/

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.Element;
import org.w3c.dom.NodeList;

public class DOMParser
{

public static void main( String[] args )
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document;
document = builder.parse( new File( "C:\\demoxml.xml" ) );
/*
* You can pass either xml file or string.To fetch the root element
* of the xml document.
*/
Element rootEle = document.getDocumentElement();
/*
* To fetch all the child nodes of the root element.
*/
NodeList childNodes = rootEle.getChildNodes();
/*
* To search an element from the whole document.
*/
NodeList parentNode = document.getElementsByTagName( "parent1" );
/*
* To create a new child element by the name "newChild".
*/
Element newChild = document.createElement( "newChild" );
/*
* Adding text data to "newChild".
*/
newChild.appendChild( document
.createTextNode( "new Child of the parent1 node" ) );

/*
* To append the "newChild" ,created above.
*/
parentNode.item( 0 ).appendChild( newChild );

TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

/*
* Preparing the source which is the document created above.
*/
Source srcDocument = new DOMSource( document );
/*
* Destination will be same different xml.
*/
Result destxml = new StreamResult( new File( "C:\\demoxml.xml" ) );
/*
* Transforming document to destination xml.
*/
aTransformer.transform( srcDocument, destxml );
System.out.println( "Successfully transformed" );
}
catch (Exception e)
{
System.out.println( "exec " + e );
}
}
}

No comments:

diggthis