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

Web Service 學習筆記:Schema 約束詳解

     編輯:Java 綜合教學

好記性不如爛筆頭。觀看 Web Service 教學影片後,整理了關於 XML Schema 約束的核心概念與實作範例,方便日後複習。

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>

關鍵元素說明

  • element:根元素宣告
  • complexType:複雜型別,允許包含子元素或屬性
  • sequence:序列,子元素必須依序出現
  • maxOccurs="unbounded":可重複出現無上限次

對應的 XML 實例

<書架>
  <書>
    <書名>JavaScript開發</書名>
    <作者>老佟</作者>
    <售價>28.00元</售價>
  </書>
  <書>
    <書名>...</書名>
    <作者>...</作者>
    <售價>...</售價>
  </書>
</書架>

Schema 規範重點

  1. 所有標籤與屬性皆需在 Schema 中定義。
  2. Schema 檔案需有唯一識別,稱為 namespace,由 targetNamespace 指定(值為 URL,不一定真實存在)。
  3. 引入 Schema 約束使用 xmlns 屬性,值為對應的 namespace。
  4. 若引入非 W3C 定義的 Schema,必須用 schemaLocation 指定檔案位置,格式為 namespace 路徑。
  5. 引入多個約束時,需為 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 設定

這與 Spring 設定檔中的 xmlns:context、xmlns:aop 等命名空間宣告邏輯相同,皆是為了引入特定 Schema 並避免衝突。


初學者筆記,歡迎指正補充。

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