tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 XML > XOM > Replcace Child

Replcace Child 

XOM (XML Object Model) is a tree based java API for processing XML by taking the best ideas from SAX and DOM. It is simple, fast and easy to use. This requires the library xom-1.2.7.jar to be in classpath. The following example shows replacing a child element with a new element.

File Name  :  

File Name  :  
Author  :  Sudhakar KV
Email  :  [email protected]
package com.bethecoder.tutorials.xom.tests;

import java.util.Date;

import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;
import nu.xom.ValidityException;

public class ReplaceChild {

   @param args
   @throws IOException 
   @throws ParsingException 
   @throws ValidityException 
  public static void main(String[] argsthrows ValidityException, ParsingException, IOException {
    Builder builder = new Builder();
    InputStream ins = ReplaceChild.class.getClassLoader()
    //Reads and parses the XML
    Document doc =;

    //Get student list
    Elements students = doc.getRootElement().getChildElements();
    Element ageChild = null;
    Element dobChild = null;
    for (int i = ; i < students.size() ; i ++) {
      ageChild = students.get(i).getFirstChildElement("age");
      if (ageChild != null) {
        dobChild = new Element("dob");
        dobChild.appendChild(new Date().toString());
        //Replace 'age' element with 'dob' element
        students.get(i).replaceChild(ageChild, dobChild);


It gives the following output,
File Name  :  OUTPUT


bl  br