XML Tutorial/XML Schema/Anonymous Custom Types

Материал из Web эксперт
Перейти к: навигация, поиск

Elements with Anonymous Complex Types

If you don"t need to reuse a complex type, it may be faster to create an anonymous complex type within the element declaration.
 
File: Schema..xsd
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://www.wbex.ru" xmlns="http://www.wbex.ru"
  elementFormDefault="qualified">
  <xsd:element name="characteristics">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="weight" type="xsd:string" />
        <xsd:element name="length" type="xsd:string" />
      </xsd:sequence>
      <xsd:attribute name="kind" type="xsd:string" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>
 
File: Data.xml
<?xml version="1.0"?>
<characteristics xmlns="http://www.wbex.ru" kind="physical">
  <weight>3 points</weight>
  <length>3 years</length>
</characteristics>


You don"t have to name every custom type

If you"re just going to use a type once, you can omit the cross reference between the element and the type.
The only difference between an anonymous type and a named type is that a named type can be used more than once. 
whereas the anonymous type can only be used for the element in which it is contained.
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://www.wbex.ru" xmlns="http://www.wbex.ru"
  elementFormDefault="qualified">
  <xsd:element name="zipcode">
    <xsd:simpleType>
      <xsd:restriction base="xsd:string">
        <xsd:pattern value="\d{5}(-\d{4})?" />
      </xsd:restriction>
    </xsd:simpleType>
  </xsd:element>
</xsd:schema>