Home Tutorial Xml Jdom JDOM Element Example, How to add and remove child from xml file.

 
 

Share on Google+Share on Google+
JDOM Element Example, How to add and remove child from xml file.
Posted on: August 26, 2010 at 12:00 AM
Advertisement
In this tutorial, you will see how to add and remove child from xml file.

JDOM Element Example, How to add and remove child from xml file.

In this tutorial, we will see how to add and remove child node in an xml Document tree. We can add child any where in xml document tree with the help of JDOM API. JDOM is a library used for manipulating xml documents.

In this example, we are discussing the use of addContent() method. Example also show how to delete a child Element. The addContent(Content child) method of Element class adds element at end of child list.

Code:

SetNewName.java

package roseindia;

import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import java.io.ByteArrayInputStream;
import java.util.List;

public class AddChild {
  public static void main(String[] args) {
String XmlFile = "<Company>" 
  + "<Employee name=\"satya\" age=\"25\"/> "
    "<Employee  name=\"bharat\" age=\"24\"/>" 
   + 
"</Company>";
    SAXBuilder builder = new SAXBuilder();
    try {
      Document document = builder
     .build
(new ByteArrayInputStream(XmlFile.getBytes()));
      document.getRootElement().addContent(
         new Element("Employee").setAttribute("key""056"));
      List<Element> childList = document.getRootElement()
      .getChildren
();
   childList.add(new Element("CompInfo").setAttribute("name",
      "Roseindia.net"));
      childList.remove(1);
    XMLOutputter outputter1 = new XMLOutputter(Format
    .getPrettyFormat
());
      outputter1.output(document, System.out);
    catch (Exception e) {
      System.out.println(e);
    }
  }
}
Output:
<?xml version="1.0" encoding="UTF-8"?>
<Company>
<Employee name="satya" age="25" />
<Employee key="056" />
<CompInfo name="Roseindia.net" />
</Company>

Download this code

Advertisement

Related Tags for JDOM Element Example, How to add and remove child from xml file.:


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 26, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com