Java JDOM库怎么用 JDOM2入门教程

11次阅读

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

Java JDOM库怎么用 JDOM2入门教程

JDOM2 是 java 中一个轻量、易用的 XML 处理库,专为开发者友好设计,比原生 DOM 更简洁,比 SAX 更直观。它不依赖 SAX 或 DOM 实现,而是自己封装了底层解析器(如 Xerces),让你专注 XML 内容操作。

添加 JDOM2 依赖

使用 Maven,在 pom.xml 中加入:


  org.jdom
  jdom2
  2.0.6

注意:JDOM2 是 JDOM 的升级版,已不再维护旧版 JDOM(1.x),务必用 jdom2 坐标。

读取 XML 文件并遍历元素

SAXBuilder 解析 XML,得到 Document 对象

立即学习Java免费学习笔记(深入)”;

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(“config.xml”));
Element root = doc.getRootElement();
List children = root.getChildren(“item”); // 获取所有 子元素
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”) 获取

text=ZqhQzanResources