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

Java DOM 解析實戰:三大常見場景完整代碼示例

     編輯:Java 綜合教學

前言

關於 DOM 解析 XML 的教程網上已經非常多,本文不再贅述基礎理論,而是針對實際開發中最常遇到的三個場景,提供可直接落地的代碼示例:

  • 如何獲取同名的多個節點
  • 如何將已獲取的節點轉換為 XML 字符串描述
  • 如何修改節點屬性的值(兩種方式對比)

本文使用 dom4j 庫進行演示,相關依賴包下載地址:

場景一:獲取多個同名節點

示例 XML 結構

<model name="model">
  <operator name="kafkaInput">
    <parameter name="inputTopicName" value="department1_tn1"/>
  </operator>
  <operator name="addFielduuid">
    <parameter name="parameter1" value="p1"/>
  </operator>
  <operator name="kafkaOutput">
    <parameter name="outTopicName" value="department1_tn1"/>
  </operator>
  <connect from="kafkaInput.outport1" to="addFielduuid.inport1"/>
  <connect from="addFielduuid.outport1" to="kafkaOutput.inport1"/>
  <output path="/home"/>
</model>

上述 XML 中,<model> 節點下包含三個同名的 <operator> 子節點。

核心代碼實現

public static void parsingSameNameNode(String xmlPath) {
    File file = new File(xmlPath);
    SAXReader reader = new SAXReader();
    Document document;
    try {
        document = reader.read(file);
        // 使用 XPath 表達式獲取 model 下所有 operator 節點
        List<Element> operators = document.selectNodes("/model/operator");
        for (Element operator : operators) {
            // 業務邏輯處理...
            String opName = operator.attributeValue("name");
            System.out.println("操作器名稱: " + opName);
        }
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

關鍵點解析

  • selectNodes(String xpath):接收 XPath 路徑,"/model/operator" 表示獲取 model 節點下所有名為 operator 的子節點
  • 返回值:List<Element>,每個 Element 代表一個節點對象,可進一步獲取屬性、子節點等信息
  • 前置準備:讀取 XML 文件並構建 Document 對象的樣板代碼如下:
File file = new File(xmlPath);
SAXReader reader = new SAXReader();
Document document;
try {
    document = reader.read(file);
    // 後續操作...
} catch (DocumentException e) {
    e.printStackTrace();
}

場景二:獲取節點的 XML 字符串描述

當解析得到某個 Element 節點後,若需將其完整結構(含子節點、屬性)輸出為 XML 格式字符串,可使用 asXML() 方法。

代碼示例

// 獲取根節點
Element rootNode = document.getRootElement();
// 獲取根節點下的 context 子節點
Element contextNode = rootNode.element("context");
// 將節點轉為 XML 字符串
String contextXml = contextNode.asXML();
System.out.println(contextXml);

執行流程

  1. 通過 document.getRootElement() 獲取 DOM 樹根節點
  2. 調用 rootNode.element("context") 定位目標子節點
  3. 調用 asXML() 將該節點及其完整子樹序列化為字符串

場景三:修改節點屬性值

DOM4J 提供了兩種修改屬性值的方式,以下以將 <output path="/home"/> 中的 path 屬性修改為 /home/BYRans 為例。

方式一:通過 Attribute 對象的 setValue()

Element rootNode = document.getRootElement();
Element outputNode = rootNode.element("output"); // 定位 output 節點
Attribute pathAttr = outputNode.attribute("path"); // 獲取 path 屬性對象
pathAttr.setValue("/home/BYRans"); // 直接修改屬性值

邏輯:定位節點 → 獲取屬性對象 → 調用 setValue() 修改值。

方式二:通過 Element 的 setAttributeValue()(不推薦)

Element rootNode = document.getRootElement();
Element outputNode = rootNode.element("output");
outputNode.setAttributeValue("path", "/home/BYRans");

注意:官方文檔標記 setAttributeValue() 為已棄用,建議優先使用方式一。此方法未來版本可能移除。

總結

掌握這三個核心場景,基本能應對 90% 的 DOM 解析業務需求。實際項目中建議封裝通用工具類,統一異常處理與資源釋放,提升代碼復用性與健壯性。

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