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

XML 數據綁定系列(一):核心概念、優勢與 Schema 定義

     編輯:Java 相關知識

數據綁定系列首篇:闡述什麼是數據綁定、為何優於 SAX/DOM/JDOM、如何用 XML Schema 定義資料契約、決策樹選擇生成類還是實例、以 Web Service 配置為例完整展示 Schema 設計與對應 Java 介面/實現結構。

三種 XML 處理方式對比

方式代表 API特點適用場景
回調/事件驅動SAX低記憶體、單向、邏輯分散大文件流式處理
樹狀結構DOM、JDOM直觀、隨機存取、大文件佔記憶體文檔轉換、結構操作
數據綁定JSR-031JavaBean 風格存取、類型安全、零 XML API 依賴配置文件、資料傳輸物件

核心決策樹

  1. XML 是否適合轉物件? → 有明確結構、屬性對應欄位 → 是
  2. 每個文檔生成新類? → 否,複用性差 → 共用類
  3. 用現有類還是生成新類? → 依據 Schema 生成可重用類

資料契約:XML Schema 定義

<schema targetNamespace="https://www.enhydra.org"
    xmlns="https://www.w3.org/1999/xmlSchema">

  <complexType name="ServiceConfiguration">
    <attribute name="name" type="string"/>
    <attribute name="version" type="float"/>
  </complexType>

  <complexType name="WebServiceConfiguration"
      baseType="ServiceConfiguration" derivedBy="extension">
    <element name="port">
      <complexType>
        <attribute name="protocol" type="string"/>
        <attribute name="number" type="integer"/>
        <attribute name="protected" type="string"/>
      </complexType>
    </element>
    <element name="document">...</element>
  </complexType>

  <element name="webServiceConfiguration" type="WebServiceConfiguration"/>
</schema>

Schema 到 Java 映射規則

  • complexType → 介面
  • attribute → 原生型別欄位(String、int、float、boolean)
  • element → 巢狀物件(再次遞歸映射)
  • baseType + extension → 介面繼承
  • 命名空間 → 套件結構

生成的 Java 結構預覽

// 基礎介面
public interface ServiceConfiguration {
    String getName(); void setName(String name);
    float getVersion(); void setVersion(float version);
}

// 擴充介面
public interface WebServiceConfiguration extends ServiceConfiguration {
    PortType getPort(); void setPort(PortType port);
    DocumentType getDocument(); void setDocument(DocumentType doc);
}

// 實現類對應:ServiceConfigurationImpl、WebServiceConfigurationImpl、PortTypeImpl...

為何選擇 XML Schema 而非 DTD

  • 支援資料型別(integer、float、date 等)
  • 支援命名空間
  • 物件導向特性:繼承、擴充、限制
  • Java 強型別天然契合

系列規劃

  1. 概念與 Schema 設計(本文)
  2. SchemaMapper 生成 Java 類
  3. Unmarshaller:XML → Java
  4. Marshaller:Java → XML

所有源碼已整合至 Enhydra 專案,開源持續維護中。

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