public class JDomReader {
public static void main(String[] args) {
SAXBuilder builder = new SAXBuilder();
try {
Document doc = builder.build(new File("test.xml"));
Element root = doc.getRootElement();
System.out.println(root.getName());
Element student = root.getChild("student");
String id = student.getAttribute("id").getValue();
System.out.println("id = " + id);
student.removeChild("username");
// List list = doc.getContent();
// System.out.println(list.size());
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent(" "));
out.output(doc, new FileWriter("result.xml"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<root>
<student id="1">
<username>张三</username>
</student>
<student id="2">
<username>李四</username>
</student>
</root>