Append 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 appending a new element as child of an existing element.
package com.bethecoder.tutorials.xom.tests;
import java.io.IOException;
import java.io.InputStream;
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 AppendChild {
/**
* @param args
* @throws IOException
* @throws ParsingException
* @throws ValidityException
*/
public static void main ( String [] args ) throws ValidityException, ParsingException, IOException {
Builder builder = new Builder () ;
InputStream ins = AppendChild. class .getClassLoader ()
.getResourceAsStream ( "student_list.xml" ) ;
//Reads and parses the XML
Document doc = builder.build ( ins ) ;
//Get student list
Elements students = doc.getRootElement () .getChildElements () ;
Element nameChild = null ;
for ( int i = 0 ; i < students.size () ; i ++ ) {
nameChild = students.get ( i ) .getFirstChildElement ( "name" ) ;
if ( nameChild != null ) {
Element email = new Element ( "email" ) ;
email.appendChild ( nameChild.getValue () + "@gmail.com" ) ;
//Append the newly created child element
students.get ( i ) .appendChild ( email ) ;
}
}
System.out.println ( doc.toXML ()) ;
}
}
It gives the following output,