數據綁定系列首篇:闡述什麼是數據綁定、為何優於 SAX/DOM/JDOM、如何用 XML Schema 定義資料契約、決策樹選擇生成類還是實例、以 Web Service 配置為例完整展示 Schema 設計與對應 Java 介面/實現結構。
| 方式 | 代表 API | 特點 | 適用場景 |
|---|---|---|---|
| 回調/事件驅動 | SAX | 低記憶體、單向、邏輯分散 | 大文件流式處理 |
| 樹狀結構 | DOM、JDOM | 直觀、隨機存取、大文件佔記憶體 | 文檔轉換、結構操作 |
| 數據綁定 | JSR-031 | JavaBean 風格存取、類型安全、零 XML API 依賴 | 配置文件、資料傳輸物件 |
<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>
complexType → 介面attribute → 原生型別欄位(String、int、float、boolean)element → 巢狀物件(再次遞歸映射)baseType + extension → 介面繼承// 基礎介面
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...
所有源碼已整合至 Enhydra 專案,開源持續維護中。