萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

JDom2 讀取數據庫生成 XML 文件完整實戰:從連接池到格式化輸出

JDom2 是 Java 操作 XML 的優雅庫 (比 DOM/JAXP 更符合 Java 風格)。本文演示:連接 MySQL → 查詢用戶表 → 構建 JDom 文檔樹 → 格式化輸出 XML 文件。

1. 依賴引入 (Maven)

<dependency>
  <groupId>org.jdom</groupId>
  <artifactId>jdom2</artifactId>
  <version>2.0.6</version> <!-- 檢查最新版 -->
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.33</version>
</dependency>

2. 數據庫連接工具類 (單例/連接池生產環境請用 HikariCP)

package cn.gov.csrc.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnection {
    private static final String URL = "jdbc:mysql://localhost/springdb?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=UTF-8";
    private static final String USER = "root";
    private static final String PASS = "root";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    static {
        try { Class.forName(DRIVER); }
        catch (ClassNotFoundException e) { throw new ExceptionInInitializerError(e); }
    }

    public static Connection getConn() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASS);
    }
}

3. 核心邏輯:查詢 → 構建 Element 樹 → 格式化輸出

package cn.gov.csrc.xml;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import cn.gov.csrc.jdbc.DatabaseConnection;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;

public class WriteXml {

    public static void writeUsersToXml(String outputPath) {
        String sql = "SELECT id, username, password, status, descn FROM user";
        
        try (Connection conn = DatabaseConnection.getConn();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql);
             FileWriter fw = new FileWriter(outputPath)) {

            Element root = new Element("users");
            
            while (rs.next()) {
                Element user = new Element("user");
                root.addContent(user);
                
                addChild(user, "id", rs.getString("id"));
                addChild(user, "username", rs.getString("username"));
                addChild(user, "password", rs.getString("password")); // 實際不應導出明文密碼!
                addChild(user, "status", rs.getString("status"));
                addChild(user, "descn", rs.getString("descn"));
            }

            Document doc = new Document(root);
            Format fmt = Format.getCompactFormat() // 或 getPrettyFormat() 縮進
                .setEncoding("UTF-8")
                .setIndent("  "); // 兩空格縮進
            
            new XMLOutputter(fmt).output(doc, fw);
            System.out.println("XML 生成成功: " + outputPath);

        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
    }

    private static void addChild(Element parent, String name, String text) {
        Element child = new Element(name);
        child.setText(text != null ? text : "");
        parent.addContent(child);
    }

    public static void main(String[] args) {
        writeUsersToXml("D:/user.xml");
    }
}

4. 生成 XML 效果示例

<?xml version="1.0" encoding="UTF-8"?>
<users>
  <user>
    <id>1</id>
    <username>admin</username>
    <password>******</password>
    <status>1</status>
    <descn>系統管理員</descn>
  </user>
  <user>
    <id>2</id>
    <username>zhangsan</username>
    <password>******</password>
    <status>1</status>
    <descn>普通用戶</descn>
  </user>
</users>

5. 關鍵最佳實踐

  1. try-with-resources:自動關閉 Connection/Statement/ResultSet/Writer,防洩漏。
  2. 密碼脫敏: 導出時**務必不寫入真實密碼**,示例中已用 ****** 替代。
  3. 大數據量分批: stmt.setFetchSize(1000) + 游標流式處理,避免 OOM。
  4. 格式化選項: Format.getPrettyFormat() (縮進換行) 適合人工閱讀/配置文件;getCompactFormat() (緊湊) 適合網絡傳輸/存儲。
  5. 命名空間支援: new Element("user", Namespace.getNamespace("ns", "https://example.com"))。
  6. XPath 查詢: XPathFactory.instance().compile("//user[id='1']", Filters.element()).evaluateFirst(doc)。

6. 替代方案對比

庫風格適合場景
JDom2樹模型、Java 風格 API中小文檔構建/修改、配置文件
DOM4J樹模型、XPath 強複雜 XML 查詢/轉換
StAX (JDK 內置)流式拉解析/寫入超大 XML、低內存、高性能
JAXB對象綁定 (Annotation)對象↔XML 序列化、WebService
Jackson XML對象綁定 (JSON 風格)統一 JSON/XML 雙格式輸出

JDom2 以直觀 API、良好泛型支援、無外部依賴 (僅 JDK) 成為輕量級 XML 處理首選。

copyright © 萬盛學電腦網 all rights reserved