Search code examples
xmlxsd

how do I restrict a value in an xml element to have a defined type?


I want to validate this xml document, with a type for the age field that can be re-used in other elements:

<Person>
  <name>joe</name>
  <age>254</age>
</Person>

The XSD file:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Age">
    <xs:simpleType>
      <xs:restriction base="xs:integer">
        <xs:minInclusive value="0" />
        <xs:maxInclusive value="100" />
      </xs:restriction>
    </xs:simpleType>
  </xs:element>
  <xs:element name="Person">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="age" type="Age"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

fails with "Src-resolve: Cannot Resolve The Name 'age' To A(n) 'type Definition' Component." If I change the type="Age" to type="xs:integer" to get the schema usable, the XML document passes when it should fail because the age is out of range.

The document

<Age>254</Age>

correctly fails because it is being checked against the Age type.

How can I get the person element to validate its age field against the Age type? (This is a toy example; the actual type represented by Age is more complex. And yes, the xsd still doesn't work if the typename is "ageRange" to be distinct from the field name "age".)

----- EDIT ------

XSD contains the example

<xs:complexType name="PurchaseOrderType">
  <xs:sequence>
   <xs:element name="shipTo" type="USAddress"/>
   <xs:element name="billTo" type="USAddress"/>
   <xs:element ref="comment" minOccurs="0"/>
   <xs:element name="items"  type="Items"/>
  </xs:sequence>
  <xs:attribute name="orderDate" type="xs:date"/>
 </xs:complexType>

so the question is how to get the type "USAddress" or "Age" to resolve when it is the type of named element content? Defining them under the same root schema should be sufficient.


Solution

  • Make age a simple type

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:simpleType name="Age">
                <xs:restriction base="xs:integer">
                    <xs:minInclusive value="0" />
                    <xs:maxInclusive value="100" />
                </xs:restriction>
        </xs:simpleType>
        <xs:element name="Person">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="name" type="xs:string"/>
                    <xs:element name="age" type="Age"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:schema>