How do I remove an attribute from XML element?

Category: org.jdom, viewed: 2243 time(s).

The following example shows you how to remove attributes from an XML element. We will remove attribute named userid from the <row> element. To remove an attribute you can call the removeAttribute(String name) method of the Element object.

package org.kodejava.example.jdom;

import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;

import java.io.File;
import java.io.IOException;

public class JDOMRemoveAttribute {
    public static void main(String[] args) {
        SAXBuilder builder = new SAXBuilder();
        try {
            //
            // <root>
            //     <row userid="alice">
            //         <firstname>Alice</firstname>
            //         <lastname>Starbuzz</lastname>
            //     </row>
            // </root>
            //
            Document doc = builder.build(new File("data.xml"));
            XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
            out.output(doc, System.out);

            //
            // Get the root element and find a child named row and remove
            // its attribute named "userid"
            //
            Element root = doc.getRootElement();
            root.getChild("row").removeAttribute("userid");
            out.output(doc, System.out);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The program will output the following result to the console:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <row userid="alice">
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
  </row>
</root>

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <row>
    <firstname>Alice</firstname>
    <lastname>Starbuzz</lastname>
  </row>
</root>
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats