JDOM Element Example, How to remove attribute of xml element in java.


 

JDOM Element Example, How to remove attribute of xml element in java.

In this tutorial, you will see how to remove attribute of xml element in java.

In this tutorial, you will see how to remove attribute of xml element in java.

JDOM Element Example, How to remove attribute of xml element in java.

In this tutorial, we will see how to remove attribute of xml element in java with the help
of JDOM library. It is a java tool kit for xml parsing.

With the help of this code, we can remove attribute of element. DOMBuilder is a
class that build a JDOMDocument of xml file. The getRootElement method of
Document class is used for accessing  root element. The
 removeAttribute(String name) method remove attribute
of an element with given name. The Element class is available
in org.jdom.Element pacakage.

Element API.

Return Type Method Description
boolean removeAttribute(String name) The removeAttribute(...) method remove attribute from existing element.

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 RemoveAttribute {
  public static void main(String[] args) {
    DOMBuilder docbuilder = new DOMBuilder();
    try {
      Document doc = docbuilder.build(new File("student.xml"));
      XMLOutputter output = new XMLOutputter();
      Element rootElement = doc.getRootElement();
      rootElement.getChild("first").removeAttribute("name");
      System.out.println("After removing attribute xml file.");
      output.output(doc, System.out);
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Output:

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

Download this code

Ads