Domanda

I need to specify an XML fragment like this:

<address type="work">...</address>
<address type="home">...</address>

The work address is required, but the home address is optional. How can I achieve that restriction in XML Schema?

This is my address complexType:

<xs:complexType name="AddressType">
  <xs:sequence>
    <xs:element name="street" type="xs:string"></xs:element>
    <xs:element name="postalCode" type="PostalCodeType"></xs:element>
    <xs:element name="town" type="xs:string"></xs:element>
  </xs:sequence>
  <xs:attribute name="type" use="required">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:enumeration value="work" />
        <xs:enumeration value="home" />
      </xs:restriction>
    </xs:simpleType>
  </xs:attribute>
</xs:complexType>

I have listed the address elements like this:

<xs:element name="address" type="AddressType"></xs:element>
<xs:element name="address" type="AddressType" minOccurs="0"></xs:element>

So, how do I specify that the first one be specifically a type="work" address, and the other one a type="home" address?

È stato utile?

Soluzione

In XSD 1.0 I do not know of a way to achieve what you say you want. (The design of XML is based on the premise that different kinds of objects are called different things; if you want home addresses and work addresses to have different validation behavior, that's good evidence that they are different things, for your purposes, and should not be called the same thing. If you name the elements WorkAddress and HomeAddress, you have no problem. Things go much better if we don't lie to the processor about what things are.)

In XSD 1.1 you can specify in the content model that 'address' must occur at least once, and use an assertion to check that the first occurrence has type="work" and the second (if it occurs) type="home".

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top