XML Tutorial/XML Schema/union

Материал из Web эксперт
Версия от 08:26, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

By declaring a <union>, you can validate the values in your instance document against multiple types.

<union memberTypes="whitespace separated list of types"> 
You specify the types you are combining by including the memberTypes attribute. 
The value of the memberTypes attribute should be a whitespace-separated list of references to global <simpleType> definitions or built-in XML Schema datatypes. 
The <union> declaration also allows you to specify your memberTypes by creating local <simpleType> definitions. 
<simpleType name="UnknownString"
  <restriction base="string"
    <enumeration value="Unknown" />
    </restriction>
</simpleType>

<simpleType name="UnknownOrFloatType"
    <union memberTypes="float contacts:UnknownString"/>
</simpleType>
<element name="latitude" type="contacts:UnknownStringOrFloatType"/> 
<element name="longitude" type="contacts:UnknownStringOrFloatType"/> 
Some valid elements include the following: 
<latitude>43.847156</latitude> 
<longitude>Unknown</longitude> 
Some invalid elements include these: 
<latitude>unknown</latitude> 
<longitude>43.847156 Unknown</longitude>


The union method joins the value spaces and lexical spaces of one or more datatypes to derive a new type

<!-- schema -->
<xsd:element name="recipe">
  <xsd:simpleType>
   <xsd:union>
    <xsd:simpleType>
    <xsd:restriction base="decimal"/>
    </xsd:simpleType>
    <xsd:simpleType>
     <xsd:restriction base="string"/>
    </xsd:simpleType>
   </xsd:union>
  </xsd:simpleType>
</xsd:element>
<!-- instance document -->
<recipe>1.5</recipe>
<recipe>cups</recipe>


When the values of a union datatype are validated, they? validated in the order in which they? defined

<!-- schema -->
<xsd:element name="dog">
  <xsd:simpleType>
   <xsd:union>
    <xsd:simpleType>
    <xsd:restriction base="nonNegativeInteger"/>
   </xsd:simpleType>
   <xsd:simpleType>
   <xsd:restriction base="string"/>
   </xsd:simpleType>
  </xsd:union>
  </xsd:simpleType>
 </xsd:element>
<!-- instance document -->
<dog>15</dog>
<dog>hound</dog>