Home Xml Replacing a Node with a New One
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Replacing a Node with a New One

Advertisement
This Example shows you how to Replace a node with existing node in a DOM document.

Replacing a Node with a New One

     

This Example shows you how to Replace a node with existing node in a DOM document. JAXP (Java API for XML Processing) is an interface which provides parsing of xml documents. Here the Document BuilderFactory is used to create new DOM parsers. These are some of the methods used in code given below for adding attribute:-

root.getFirstChild().getFirstChild().getNodeName():-Access the subchild name of the root.

Node schild = fchild.getNextSibling():-it returns the node immediately following the node fchild.

root.replaceChild(schild, fchild):-This method replaces a child node with another.

Xml code for the program generated is:-

<?xml version="1.0" encoding="UTF-8"?>
<Company>
    <Location>
        <Companyname>Roseindia .Net</Companyname>
        <Employee>Girish Tewari</Employee>
    </Location>
    <Id></Id>>
</Company>


Replacenode.java

/* 
 * @Program that Replace an Existing Node with a New One
 * Replacenode.java 
 * Author:-RoseIndia Team
 * Date:-09-Jun-2008
 */

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class Replacenode {

  public static void main(String[] args) throws Exception {
  DocumentBuilderFactory factory = 
  DocumentBuilderFactory.newInstance();

  Document doc = factory.newDocumentBuilder().parse(
  
new File("Document4.xml"));
  new Replacenode().replacePerson(doc);
  }

  public void replacePerson(Document doc) {

  Element root = doc.getDocumentElement();

  System.out.println("Node before replacing is :" +
  root.getFirstChild().getFirstChild().getNodeName());

  Node fchild = root.getFirstChild();
  //finds the next child of the fchild
  Node schild = fchild.getNextSibling();
  
  //Replaces the fchild with schild  
  root.replaceChild(schild, fchild);

  System.out.println("Node after replacing name is:" +
  root.getFirstChild().getNodeName());

  }
}


Output of the program:-

Node before replacing is :Companyname
Node after replacing name is:Id


Download SourceCode

     

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  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.

Posted on: August 24, 2008

Related Tutorials

Ask Questions?    Discuss: Replacing a Node with a New One   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com