JDOM Element Example, How to remove child of an element from xml file in java.


 

JDOM Element Example, How to remove child of an element from xml file in java.

In this tutorial, you will see how to remove child of an element from xml file in java.

In this tutorial, you will see how to remove child of an element from xml file in java.

JDOM Element Example, How to remove child of an element from xml file in java.

In this tutorial, we will see how to remove child of an element from xml file in
java with the help of JDOM library. JDOM is a java toolkit for manipulating,
 creating and serializing  xml file.

With the help of this java code, we can remove a child of given element. The
DOMBuilder class is used for creating DOM tree. The getRootElement
method returns root of document. The removeChild(String name) method
 of Element class is used for removing child of an element.

Element API.

Return Type Method Description
boolean removeChild(String name) The removeChild(...) method remove child    element of given name from existing xml file.

Code:

student.xml

<?xml version="1.0"?>
<Student >
    <first name="bharat" id="10">
    <city>Bly</city>
     </first>
    <first name="ankit" id="20" >
    <city>lko</city>
    </first>
    <first name="gyan" id="30">
    <city>lko</city>
    </first>
</Student>

CloneAttribute.java

package roseindia;

import java.io.File;
import org.jdom.input.DOMBuilder;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class RemoveElement {
  public static void main(String[] args) {
    DOMBuilder docbuilder = new DOMBuilder();
  File file=new File("student.xml");
    try {
      Document doc = docbuilder.build(file);
      Element rootElement = doc.getRootElement();
      boolean childRemove=rootElement.removeChild("first");
    if(childRemove){
      XMLOutputter output = new XMLOutputter();
      System.out.println("After removing element xml file.");
      output.output(doc, System.out);
    else
    {
      System.out.println("Elenemt not removed");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Output:

After removing element xml file.
<?xml version="1.0" encoding="UTF-8"?>
<Student>
first id="20" name="ankit">
<city>lko</city>
</first>
<first id="30" name="gyan">
<city>lko</city>
</first>
</Student>

Download this code

Ads