Java如何从JDOM中的XML元素中删除属性?

下面的示例向您展示如何从XML元素中删除属性。我们将从元素中删除命名userid的属性<row>。要删除属性,可以调用对象的removeAttribute(String name)方法Element。

package org.nhooo.example.jdom;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.File;

public class JDOMRemoveAttribute {
    public static void main(String[] args) {
        SAXBuilder builder = new SAXBuilder();
        try {
            // <?xml version="1.0" encoding="UTF-8"?>
            // <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);

            // 获取根元素并找到一个名为row的子项并删除
            // 其属性名为“ userid”"userid"
            Element root = doc.getRootElement();
            root.getChild("row").removeAttribute("userid");
            out.output(doc, System.out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

该程序将以下结果输出到控制台:

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <row>
    <username>alice</username>
    <password>secret</password>
  </row>
</data>
<?xml version="1.0" encoding="UTF-8"?>
<data>
  <row>
    <username>alice</username>
    <password>secret</password>
  </row>
</data>

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar -->
<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>

Maven中央