Schema 是一組規則的集合,也有人稱之為語法或語彙,內容包含型別定義(簡單型別與複雜型別)以及元素與屬性的宣告。由於同一份 XML 文件中可能存在來自不同來源、描述不同元素的語彙,因此需要靠命名空間(namespace)與前綴來消除元素及屬性宣告之間的歧義。當你同時使用多個命名空間的 Schema 時,能否正確分辨元素與屬性的所屬,是最基礎也最關鍵的功夫。
命名空間通常由一串 URI 形式的字串來識別,例如 urn:www.microsoft.com、https://www.xml.org.cn、https://www.w3.org/2001/XMLSchema 或 uuid:1234567890。它只是一個識別名稱,並不要求該位置真的有資源存在。
Schema 的開頭是一段導言,之後才是正式宣告。在 schema 元素的導言中,可能出現三個常用的屬性:
<schema
xmlns="https://www.w3.org/2001/XMLSchema"
xmlns:xsd="https://www.w3.org/2001/XMLSchema-datatypes"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instances"
version="1.0">
</schema>
前兩個屬性用命名空間標識 W3C 的兩份 Schema 規範:第一個 xmlns 帶入基本的 Schema 元素,如 element、attribute、complexType、group、simpleType 等;第二個 xmlns 則定義標準的資料型別,如 string、float、integer 等。
任何一份 XSD 文件都有一個最頂層的 schema 元素,而這個元素的定義必須包含下列命名空間:
https://www.w3.org/2001/XMLSchema
至於作為宣告中元素或屬性前綴的識別名稱,你可以自行決定,並非一定要用 xsd 或 xsi。
以 student.xsd 為例,它的序言是這樣的:
<schema xmlns="https://www.w3.org/2001/XMLSchema"
xmlns:sl="https://www.xml.org.cn/namespaces/StudentList"
targetNamespace="https://www.xml.org.cn/namespaces/StudentList">
這裡的 targetNamespace 屬性表示該 Schema 所對應的命名空間 URI。也就是說,其他文件要引用這份 Schema 並宣告命名空間時,URI 必須等於這個屬性值。由於文件中會用到 student.xsd 自行定義的擴充型別,所以也宣告了 xmlns:sl="https://www.xml.org.cn/namespaces/StudentList"。
接著看由這份 Schema 規範的 XML 實例文件,開頭會是這樣:
<studentlst
xmlns="https://www.xml.org.cn/namespaces/StudentList"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.xml.org.cn/namespaces/StudentList student.xsd">
其中預設命名空間宣告 xmlns="https://www.xml.org.cn/namespaces/StudentList" 正是與先前 Schema 宣告的命名空間相結合,用來約束這份文件;xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" 則是任何 XML 實例文件都具備的固有命名空間,其前綴名稱同樣可自行更換;而 xsi:schemaLocation 用來指明該命名空間所對應的 Schema 檔案位置,這裡表示它位於相同路徑下的 student.xsd。
把這三個部分放在一起看就很清楚了:Schema 用 targetNamespace 宣告自己負責哪個命名空間,實例文件用預設 xmlns 宣告自己歸屬哪個命名空間,再用 schemaLocation 把兩者接上,驗證工具才知道該拿哪一份 Schema 來檢查哪一段內容。