Saturday, December 6, 2008

Parse and replace the XML elements using java

This example helps to find the xml tag values and replace with new values at runtime

Prerequisites

Following jar files are required in the class path in order to run this application J

1)      xalan-2.6.0.jar

2)      xercesImpl.jar

3)      example.xml

In this example I am using java 1.6

 

Example.xml

<Request xmlns="http://javatch.blogspot.com">

      <Details>

      <name>James</name>

      <pin>9901260200041906233</pin>

      <contact>1234567890</contact>

      </Details>

      <Details>

      <name>Bill</name>

      <pin>7701260200041906244</pin>

      <contact>0987654321</contact>

      </Details>

</Request>

 

This java application tries to find out the <pin> element from xml and replace with new value to this element

package com.javatch.xml;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.io.StringWriter;

import java.util.Iterator;

import java.util.Random;

import javax.xml.namespace.NamespaceContext;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.XMLSerializer;

import org.apache.xpath.XPathAPI;

import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

import com.sun.org.apache.xml.internal.utils.PrefixResolver;

import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault;

 

public class XMLUpdate {

     

      InputStream stream = null;

      DocumentBuilderFactory xmlFact = null;

      DocumentBuilder builder = null;

      Document doc = null;

      NamespaceContext ctx = null;

     

      public XMLUpdate() {

                  initialization();

 

      }

      private void initialization(){

            try {

      stream = new FileInputStream(new File("example.xml"));

            if(stream == null) {

                  System.out.println("Cannot find xml file" + "example.xml");

                  return;

            }

        xmlFact = DocumentBuilderFactory.newInstance();

        xmlFact.setNamespaceAware(false);

        builder = xmlFact.newDocumentBuilder();

        doc = builder.parse(stream);

        // following declaring is required if there is any namespace in your xml

        final PrefixResolver resolver = new PrefixResolverDefault(doc.getDocumentElement());

              ctx = new NamespaceContext() {

                  public String getNamespaceURI(String prefix) {

                      return resolver.getNamespaceForPrefix(prefix);

                  }

                  public Iterator getPrefixes(String val) {

                      return null;

                  }

                  // Dummy implemenation - not used!

                  public String getPrefix(String uri) {

                      return null;

                  }

              };

            }catch(ParserConfigurationException pce) {

                 

            } catch (FileNotFoundException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            } catch (SAXException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            } catch (IOException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

            }

      }

      private void xmlTagValueReplace(){

        try {

            String xpathStr = "/Request/Details/pin";

            NodeList nodes =  XPathAPI.selectNodeList(doc, xpathStr);

            for(int i=0; i<nodes.getLength(); i++) {

                  nodes.item(i).setTextContent((new Random().nextInt())+"");

            }

                StringWriter stringOut = new StringWriter ();

                XMLSerializer serial = new XMLSerializer();

                serial.setOutputCharStream(stringOut);

                serial.serialize(doc);

                System.out.println(stringOut.toString());

        }catch (Exception ex) {

                ex.printStackTrace();

        }

      }

      public static void main(String args[]) {

                  XMLUpdate update = new XMLUpdate();

                  update.xmlTagValueReplace();

      }

 

}