| API | 風格 | 學習曲線 | 內存佔用 | 推薦場景 |
|---|---|---|---|---|
| DOM (W3C) | 樹模型 | 中等 | 高 (全量載入) | 小文件、需隨機訪問 |
| SAX | 事件流 | 較高 | 極低 | 大文件、單向讀取 |
| StAX | 拉取流 | 中等 | 低 | 大文件、需控制解析 |
| JDOM2 | Java 原生樹模型 | 極低 | 中等 | 中小文件、構建/修改 XML |
| DOM4J | 樹模型 | 低 | 中等 | Hibernate 等老項目 |
| JAXB | 綁定映射 | 中等 | 中等 | 對象↔XML 深度綁定 |
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6.1</version>
</dependency>
Document:XML 文檔根節點Element:元素節點 (標籤),可包含屬性、子元素、文本Attribute:屬性節點XMLOutputter:文檔輸出器 (格式化、編碼控制)Format:輸出格式配置 (縮進、換行、編碼)import org.jdom2.*;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;
public class BookCatalogGenerator {
static class Book {
String id, title, author, isbn, price, publishDate;
Book(String id, String title, String author, String isbn, String price, String publishDate) {
this.id = id; this.title = title; this.author = author;
this.isbn = isbn; this.price = price; this.publishDate = publishDate;
}
}
public static void main(String[] args) {
List<Book> books = Arrays.asList(
new Book("1", "Effective Java", "Joshua Bloch", "978-0134685991", "45.00", "2018-01-06"),
new Book("2", "Java Concurrency in Practice", "Brian Goetz", "978-0321349606", "52.00", "2006-05-09"),
new Book("3", "Clean Code", "Robert C. Martin", "978-0132350884", "48.00", "2008-08-01")
);
try {
// 1. 創建根元素
Element root = new Element("catalog")
.setAttribute("xmlns", "https://example.com/book-catalog")
.setAttribute("version", "1.0")
.setAttribute("generated", LocalDate.now().toString());
Document doc = new Document(root);
// 2. 遍歷數據構建子元素
for (Book book : books) {
Element bookElem = new Element("book")
.setAttribute("id", book.id);
// 添加子元素 (鏈式調用)
bookElem.addContent(new Element("title").setText(book.title))
.addContent(new Element("author").setText(book.author))
.addContent(new Element("isbn").setText(book.isbn))
.addContent(new Element("price")
.setAttribute("currency", "USD")
.setText(book.price))
.addContent(new Element("publishDate").setText(book.publishDate));
root.addContent(bookElem);
}
// 3. 配置輸出格式
Format format = Format.getPrettyFormat()
.setEncoding("UTF-8")
.setIndent(" ") // 4 空格縮進
.setLineSeparator("\n");
// 4. 輸出到文件
XMLOutputter outputter = new XMLOutputter(format);
try (FileOutputStream fos = new FileOutputStream("books.xml")) {
outputter.output(doc, fos);
}
// 5. 同時輸出到控制檯預覽
outputter.output(doc, System.out);
System.out.println("\n✅ XML 文件生成成功: books.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="https://example.com/book-catalog" version="1.0" generated="2024-01-15">
<book id="1">
<title>Effective Java</title>
<author>Joshua Bloch</author>
<isbn>978-0134685991</isbn>
<price currency="USD">45.00</price>
<publishDate>2018-01-06</publishDate>
</book>
<book id="2">
<title>Java Concurrency in Practice</title>
<author>Brian Goetz</author>
<isbn>978-0321349606</isbn>
<price currency="USD">52.00</price>
<publishDate>2006-05-09</publishDate>
</book>
<book id="3">
<title>Clean Code</title>
<author>Robert C. Martin</author>
<isbn>978-0132350884</isbn>
<price currency="USD">48.00</price>
<publishDate>2008-08-01</publishDate>
</book>
</catalog>
Namespace ns = Namespace.getNamespace("book", "https://example.com/book");
Element root = new Element("catalog", ns);
// 子元素繼承父命名空間,或顯式指定
Element book = new Element("book", ns);
Element desc = new Element("description");
desc.addContent(new CDATA("包含 等特殊字符"));
root.addContent(new Comment("此文件由系統自動生成,請勿手動修改"));
doc.setDocType(new DocType("catalog", "catalog.dtd")); // DTD 引用
String xmlString = new XMLOutputter(Format.getPrettyFormat()).outputString(doc);
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("books.xml"));
Element root = doc.getRootElement();
List<Element> books = root.getChildren("book");
for (Element book : books) {
String title = book.getChildText("title");
String price = book.getChild("price").getValue(); // 含屬性
String currency = book.getChild("price").getAttributeValue("currency");
}
createBookElement(Book) 方法XMLOutputter.output(Element, OutputStream) 流式輸出單個元素JDOMException、IOExceptionJDOM2 以純 Java 風格 API、鏈式調用、直觀的樹模型,成為 Java 生成/修改 XML 文件的首選輕量級庫。本文展示了從數據對象到格式化 XML 文件的完整流程,涵蓋屬性、命名空間、CDATA、註釋等實戰技巧。對於「對象 → XML」的固定結構轉換,若需更強類型綁定,可考慮 JAXB;但對於靈活構建、臨時生成、配置文件導出等場景,JDOM2 開發效率最高。