ユーザ定義データ型について。
単純型(simpleType)の定義
単純型というのは属性も子要素ももたない型のことで、
<name>やまだたろう</name>
とか
<date>2010-03-20<date>
のように要素の中に値だけをもつ型。
組み込みの単純型もいろいろ用意されていて、たとえば上のname要素なら string, date要素なら date といった型を使えばいい。
基本は組み込みの単純型で、許容する値を制限したいときは、組み込み型に制約を加えた派生型を定義することができる。それが simpleType というXML Schemaの要素。
Ex 1) integer 型で、値を 1 ~ 99 までに制限したい。
<xsd:simpleType name="MyInteger" base="xsd:integer">
<xsd:minInclusive value="1"/>
<xsd:maxInclusive value="99"/>
</xsd:simpleType>
Ex 2) string 型で、正規表現を使って値を特定のパターンに制限したい。
<xsd:simpleType name="Sku" base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:simpleType>
いきなり出てきた xsd:minInclusive とか xsd:maxInclusive とか xsd:pattern とかは、ファセットといって単純型の制限に使われる。ファセットは全部で14種類あって、各組み込み型ごとに使えるファセットが決まっている(すべてのファセットのリスト)。
複合型の定義
複合型は子要素や属性をもつ型のことで、complexType 要素で定義する。どんな子要素を含むか、に element 要素を、どんな属性を含むか、に attribute 要素を使う。
<xsd:complexType name="Address" >
<xsd:element name="name" type="xsd:string" />
<xsd:element name="street" type="xsd:string" />
<xsd:element name="city" type="xsd:string" />
<xsd:element name="state" type="xsd:string" />
<xsd:element name="zip" type="xsd:decimal" />
<xsd:attribute name="country" type="xsd:NMTOKEN"
use="fixed" value="US"/>
</xsd:complexType>
この例は、Address型という複合型を定義していて、Address型は
- string型のname要素
- string型のstreet要素
- string型のcity要素
- string型のstate要素
- decimal型のzip要素
- NMTOKEN型のcountry属性
をもつ。この例では単純型の子要素しか含まないけれど、もちろん複合型の子要素を含むこともできる(XMLでは入れ子階層をいくらでも深くできるので)。
このAddress型のインスタンスとなるXML要素の例。
<shipTo country="US">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
複合型にはいくつかバリエーションがある。
1.単純型に属性をもたせたい
次のように、単純型から派生した複合型を作る。
<xsd:element name='internationalPrice'>
<xsd:complexType base='xsd:decimal' derivedBy='extension'>
<xsd:attribute name='currency' type='xsd:string' />
</xsd:complexType>
</xsd:element>
2.空要素(子要素も値ももたず、属性だけをもつ複合型)
HTMLの<img>タグのような型。
次のように、content='empty' を指する。
<xsd:element name='internationalPrice'>
<xsd:complexType content='empty'>
<xsd:attribute name='currency' type='xsd:string' />
<xsd:attribute name='value' type='xsd:decimal' />
</xsd:complexType>
</xsd:element>
3.文字データと子要素を混在させたい
HTMLの<p>タグのような型。
次のように、content='mixed' を指定する。
<xsd:element name='letterBody'>
<xsd:complexType content='mixed'>
<xsd:element name='salutation'>
<xsd:complexType content='mixed'>
<xsd:element name='name' type='xsd:string'/>
</xsd:complexType>
</xsd:element>
<xsd:element name='quantity' type='xsd:positiveInteger'/>
<xsd:element name='productName' type='xsd:string'/>
<xsd:element name='shipDate' type='xsd:date' minOccurs='0'/>
<!-- etc -->
</xsd:complexType>
</xsd:element>
0 件のコメント:
コメントを投稿