好記性不如爛筆頭。觀看 Web Service 教學影片後,整理了關於 XML Schema 約束的核心概念與實作範例,方便日後複習。
XML Schema(.xsd)用於定義 XML 文件的結構、資料型別與約束規則。以下範例定義一個「書架」結構,包含多本「書」,每本書有書名、作者、售價。
<schema xmlns="https://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.atguigu.com/bookSchema"
elementFormDefault="qualified">
<element name="書架">
<complexType>
<sequence maxOccurs="unbounded">
<element name="書">
<complexType>
<sequence>
<element name="書名" type="string" />
<element name="作者" type="string" />
<element name="售價" type="string" />
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
<書架>
<書>
<書名>JavaScript開發</書名>
<作者>老佟</作者>
<售價>28.00元</售價>
</書>
<書>
<書名>...</書名>
<作者>...</作者>
<售價>...</售價>
</書>
</書架>
targetNamespace 指定(值為 URL,不一定真實存在)。xmlns 屬性,值為對應的 namespace。schemaLocation 指定檔案位置,格式為 namespace 路徑。n-1 個取別名(如 xmlns:dd),避免衝突。<?xml version="1.0" encoding="UTF-8"?> <書架 xmlns="https://www.atguigu.com/bookSchema" xmlns:dd="https://www.w3.org/2001/XMLSchema-instance" dd:schemaLocation="https://www.atguigu.com/bookSchema book.xsd"> ... </書架>
注意:schemaLocation 屬於 W3C 規範,故必須引入 xmlns:dd="https://www.w3.org/2001/XMLSchema-instance"。
這與 Spring 設定檔中的 xmlns:context、xmlns:aop 等命名空間宣告邏輯相同,皆是為了引入特定 Schema 並避免衝突。
初學者筆記,歡迎指正補充。