首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 生成 XML 文件實戰:JDOM2 輕量級 API 完整指南

     編輯:Java 相關知識

為什麼選擇 JDOM2?

API風格學習曲線內存佔用推薦場景
DOM (W3C)樹模型中等高 (全量載入)小文件、需隨機訪問
SAX事件流較高極低大文件、單向讀取
StAX拉取流中等低大文件、需控制解析
JDOM2Java 原生樹模型極低中等中小文件、構建/修改 XML
DOM4J樹模型低中等Hibernate 等老項目
JAXB綁定映射中等中等對象↔XML 深度綁定

Maven 依賴

<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>

進階技巧

1. 命名空間處理

Namespace ns = Namespace.getNamespace("book", "https://example.com/book");
Element root = new Element("catalog", ns);
// 子元素繼承父命名空間,或顯式指定
Element book = new Element("book", ns);

2. CDATA 區塊

Element desc = new Element("description");
desc.addContent(new CDATA("包含  等特殊字符"));

3. 註釋與處理指令

root.addContent(new Comment("此文件由系統自動生成,請勿手動修改"));
doc.setDocType(new DocType("catalog", "catalog.dtd")); // DTD 引用

4. 直接輸出字符串 (用於 API 響應)

String xmlString = new XMLOutputter(Format.getPrettyFormat()).outputString(doc);

5. 解析 XML (反向操作)

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");
}

最佳實踐總結

  1. 複用 Element 創建邏輯:封裝 createBookElement(Book) 方法
  2. 大文件分批寫入:配合 XMLOutputter.output(Element, OutputStream) 流式輸出單個元素
  3. 編碼統一:全鏈路 UTF-8 (文件、數據庫、網絡)
  4. 異常處理:捕獲 JDOMException、IOException
  5. 選擇合適 API:超大 XML (GB 級) 改用 StAX 流式寫入

總結

JDOM2 以純 Java 風格 API、鏈式調用、直觀的樹模型,成為 Java 生成/修改 XML 文件的首選輕量級庫。本文展示了從數據對象到格式化 XML 文件的完整流程,涵蓋屬性、命名空間、CDATA、註釋等實戰技巧。對於「對象 → XML」的固定結構轉換,若需更強類型綁定,可考慮 JAXB;但對於靈活構建、臨時生成、配置文件導出等場景,JDOM2 開發效率最高。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved