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

JavaWeb 使用 JDom2 解析 XML 完整教程:創建、讀取、複雜嵌套結構查詢

     編輯:Java 相關知識

JDom2 是純 Java 實現的 XML 處理庫,API 直觀、記憶體佔用少、支援 XPath、命名空間、輸出格式化。本文涵蓋:創建 XML 文件、讀取解析、複雜嵌套結構(多層 Key-Value)查詢三大核心場景,附完整可運行代碼。

1. 環境準備

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6</version>
</dependency>

2. 創建 XML 文件

public class CreateXmlDemo {
    public static void main(String[] args) throws IOException {
        // 根元素
        Element root = new Element("people");
        // 子元素 + 屬性 + 文本
        Element student = new Element("student");
        student.setAttribute("name", "張三");
        student.setAttribute("salary", "8000");
        student.setText("呵呵");
        
        root.addContent(student);
        
        // 文檔對象
        Document doc = new Document(root);
        
        // 格式化輸出
        Format format = Format.getCompactFormat();
        format.setEncoding("UTF-8");
        format.setIndent("    "); // 4 空格縮進
        
        XMLOutputter outputter = new XMLOutputter(format);
        outputter.output(doc, new FileOutputStream("people.xml"));
        System.out.println("創建成功");
    }
}

/* 輸出:


    呵呵

*/

3. 讀取解析 XML

public class ReadXmlDemo {
    public static void main(String[] args) throws JDOMException, IOException {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(new File("people.xml"));
        
        Element root = doc.getRootElement(); // 
        List<Element> students = root.getChildren("student");
        
        for (Element e : students) {
            System.out.println("name: " + e.getAttributeValue("name"));
            System.out.println("salary: " + e.getAttributeValue("salary"));
            System.out.println("text: " + e.getTextTrim());
        }
    }
}

4. 複雜嵌套結構查詢實戰

目標 XML 結構:

<Configuration>
  <Key Name="China">
    <Value Name="PhotoIDWidth">38</Value>
    <Key Name="Adult">...</Key>
    <Key Name="Child">
      <Value Name="HeadPercent">0.60</Value>
    </Key>
  </Key>
  <Key Name="Australia">...</Key>
</Configuration>

查詢邏輯:遍歷一級 Key → 取 PhotoIDWidth → 進入 Child Key → 取 HeadPercent

public class ComplexXmlQuery {
    public static void main(String[] args) throws Exception {
        SAXBuilder sb = new SAXBuilder();
        Document doc = sb.build(ComplexXmlQuery.class.getClassLoader()
            .getResourceAsStream("nation.xml"));
        
        Element root = doc.getRootElement(); // Configuration
        List<Element> keys = root.getChildren("Key"); // 所有國家 Key
        
        for (Element country : keys) {
            String countryName = country.getAttributeValue("Name");
            System.out.print(countryName);
            
            // 1. 直接子 Value:PhotoIDWidth
            for (Element val : country.getChildren("Value")) {
                if ("PhotoIDWidth".equals(val.getAttributeValue("Name"))) {
                    System.out.print(" ← " + val.getAttributeValue("Name") 
                        + ": " + val.getTextTrim());
                }
            }
            
            // 2. 嵌套 Key → Child → HeadPercent
            for (Element subKey : country.getChildren("Key")) {
                if ("Child".equals(subKey.getAttributeValue("Name"))) {
                    for (Element val : subKey.getChildren("Value")) {
                        if ("HeadPercent".equals(val.getAttributeValue("Name"))) {
                            System.out.println(" ← Child.HeadPercent: " + val.getTextTrim());
                        }
                    }
                }
            }
        }
    }
}

/* 輸出:
China ← PhotoIDWidth: 38 ← Child.HeadPercent: 0.60
Australia ← PhotoIDWidth: 35 ← Child.HeadPercent: 0.711
Austria ← PhotoIDWidth: 35 ← Child.HeadPercent: 0.689
*/

JDom2 核心包結構

  • org.jdom2:核心類
  • org.jdom2.input:SAXBuilder/DOMBuilder/StAXBuilder
  • org.jdom2.output:XMLOutputter/DOMOutputter/StAXOutputter
  • org.jdom2.filter:Filter/ElementFilter 等
  • org.jdom2.transform:XSLT 轉換
  • org.jdom2.xpath:XPath 支援(JDom 2.x 內建)

優勢總結

  • 純 Java 實現,無本地依賴
  • API 符合 Java 集合習慣(List、Iterator)
  • 支援流式處理大文件
  • 輸出格式化控制精細(縮進、編碼、換行)

JDom2 是 Java 處理中小型 XML 配置文件的優雅選擇。

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