本示例说明如何从XML文档中删除元素。在下面的代码片段中,我们首先加载XML文档并显示其原始内容。之后,我们找到元素<row>,并<address>从中删除该元素。为了获得第一个孩子,我们正在使用getChild()根Element对象中的方法。要删除元素,我们使用removeChild()方法。
package org.nhooo.example.jdom; import org.jdom2.Document; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import java.io.File; public class JDOMRemoveElement { public static void main(String[] args) { SAXBuilder builder = new SAXBuilder(); try { Document doc = builder.build(new File("userinfo.xml")); // 下面的行输出原始的userinfo.xml内容 // // <?xml version="1.0" encoding="UTF-8"?> // <rows> // <row> // <firstname>Alice</firstname> // <lastname>Mallory</lastname> // <address>Sunset Road</address> // </row> // </rows> XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); out.output(doc, System.out); //从Alice信息中删除地址元素。首先我们 // 从根元素获取行元素,最后 //从行中删除地址。结果将是: // // <?xml version="1.0" encoding="UTF-8"?> // <rows> // <row> // <firstname>Alice</firstname> // <lastname>Mallory</lastname> // </row> // </rows> doc.getRootElement().getChild("row").removeChild("address"); out.output(doc, System.out); } catch (Exception e) { e.printStackTrace(); } } }
该代码段显示以下输出:
<?xml version="1.0" encoding="UTF-8"?> <rows> <row> <firstname>Alice</firstname> <lastname>Starbuzz</lastname> <address>Sunset Road</address> </row> </rows> <?xml version="1.0" encoding="UTF-8"?> <rows> <row> <firstname>Alice</firstname> <lastname>Starbuzz</lastname> </row> </rows>
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>