JDOM 是純 Java 的 XML 處理 API,遵循「20% 功能解決 80% 問題」原則:
Document、Element、Attribute 直接對應 XML 結構。jdom-b8.zip),解壓取出 build/jdom.jar。JRE/lib/ext 或專案 WEB-INF/lib、Tomcat common/lib。mssqlserver.jar 放入 Tomcat lib。| 包 | 關鍵類別 | 用途 |
|---|---|---|
org.jdom | Document, Element, Attribute, Text, Comment, DocType | 建構、遍歷、修改 XML 樹 |
org.jdom.output | XMLOutputter, DOMOutputter | XML 文字輸出、轉換為 W3C DOM 樹 |
org.jdom.input | SAXBuilder, DOMBuilder | 從檔案/流解析 XML 建立 JDOM 樹 |
CREATE TABLE Customer (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100),
phone VARCHAR(20),
address VARCHAR(200)
);
<%@ page import="java.sql.*, org.jdom.*, org.jdom.output.*" %>
<%
response.setContentType("text/xml; charset=UTF-8");
// 1. 建立 Document 與根元素
Document doc = new Document();
Element root = new Element("customers");
doc.setRootElement(root);
// 2. 資料庫查詢
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:DB_CUSTOM", "lgz", "");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Customer");
// 3. 遍歷結果集,建構 XML 樹
while (rs.next()) {
Element customer = new Element("customer");
customer.setAttribute(new Attribute("id", rs.getString("id")));
customer.addContent(new Element("name").setText(rs.getString("name")));
customer.addContent(new Element("email").setText(rs.getString("email")));
customer.addContent(new Element("phone").setText(rs.getString("phone")));
customer.addContent(new Element("address").setText(rs.getString("address")));
root.addContent(customer);
}
// 4. 輸出 XML
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(doc, response.getOutputStream());
rs.close(); stmt.close(); con.close();
%>
<?xml version="1.0" encoding="UTF-8"?>
<customers>
<customer id="1">
<name>張三</name>
<email>zhang@example.com</email>
<phone>02-12345678</phone>
<address>台北市信義區...</address>
</customer>
<customer id="2">...</customer>
</customers>
模板驅動:腳本語言嵌入 SQL → 動態構建 XML → XSLT 轉換為 HTML/PDF/其他格式。支援多渠道輸出(Web、行動、列印)。
同一 XML 資料源 + 多個 XSL 樣式表 = 多種視圖(表格、圖表、報表、表單)。無需重寫程式碼即可變更呈現邏輯。
DataSource 替代 DriverManager,提升併發效能。try-with-resources 確保資源釋放,異常時輸出標準錯誤 XML 格式。JDOM 以 Java 原生 API 橋接關係資料庫與 XML 世界,使「資料庫 → XML → 多格式輸出」管道構建極為簡單。掌握 Document/Element/Attribute 樹操作與 XMLOutputter 輸出,即可實現靈活的資料交換與呈現層解耦。現代架構中,此模式演變為 RESTful API 直接回傳 JSON/XML,但 JDOM 於舊系統整合、報表生成、離線文檔產出仍具實用價值。