JDOM2 是轻量易用的 XML 处理库,需用 Maven 引入 jdom2 坐标;支持 SAXBuilder 解析、XMLOutputter 写入、命名空间及属性操作。

JDOM2 是 Java 中一个轻量、易用的 XML 处理库,专为开发者友好设计,比原生 DOM 更简洁,比 SAX 更直观。它不依赖 SAX 或 DOM 实现,而是自己封装了底层解析器(如 Xerces),让你专注 XML 内容操作。
添加 JDOM2 依赖
使用 Maven,在 pom.xml 中加入:
注意:JDOM2 是 JDOM 的升级版,已不再维护旧版 JDOM(1.x),务必用 jdom2 坐标。
读取 XML 文件并遍历元素
用 SAXBuilder 解析 XML,得到 Document 对象:
立即学习“Java免费学习笔记(深入)”;
享有盛誉的PHP高级教程,Zend Framework核心开发人员力作,深入设计模式、PHP标准库和JSON 。 今天,PHP已经是无可争议的Web开发主流语言。PHP 5以后,它的面向对象特性也足以与Java和C#相抗衡。然而,讲述PHP高级特性的资料一直缺乏,大大影响了PHP语言的深入应用。 本书填补了这一空白。它专门针对有一定经验的PHP程序员,详细讲解了对他们最为重要的主题
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("config.xml"));
Element root = doc.getRootElement();
List
for (Element item : children) {
String name = item.getChildText("name"); // 获取
String value = item.getAttributeValue("id"); // 获取 id 属性值
System.out.println(name + " → " + value);
}
创建和写入 XML
从零构建 XML 结构后保存到文件:
Element root = new Element("config");
Document doc = new Document(root);
Element item = new Element("item").setAttribute("type", "user");
item.addContent(new Element("name").setText("Alice"));
root.addContent(item);
XMLOutputter xmlOutput = new XMLOutputter(Format.getPrettyFormat());
xmlOutput.output(doc, new FileOutputStream("output.xml"));
关键点:
- 使用 addContent() 添加子元素或文本
- XMLOutputter 控制格式(是否缩进、编码等)
- 默认输出 UTF-8,如需其他编码,用 Format.setEncoding("GBK")
处理命名空间和属性
JDOM2 对命名空间支持清晰:
Namespace ns = Namespace.getNamespace("x", "http://example.com/ns");
Element root = new Element("root", ns);
Element child = new Element("child", ns).setAttribute("lang", "zh");
root.addContent(child);
获取带命名空间的元素时,必须用对应 Namespace 实例:
root.getChild("child", ns) —— 直接用字符串会找不到
属性无需指定命名空间即可用 getAttributeValue("lang") 获取









