views:

530

answers:

2

I have an XML schema that includes multiple addresses:

<xs:element name="personal_address" maxOccurs="1">
  <!-- address fields go here -->
</xs:element>
<xs:element name="business_address" maxOccurs="1">
  <!-- address fields go here -->
</xs:element>

Within each address element, I include a "US State" enumeration:

<xs:simpleType name="state">
    <xs:restriction base="xs:string">
     <xs:enumeration value="AL" />
     <xs:enumeration value="AK" />
     <xs:enumeration value="AS" />
                ....
            <xs:enumeration value="WY" />
        </xs:restriction>
</xs:simpleType>

How do I go about writing the "US State" enumeration once and re-using it in each of my address elements? I apologize in advance if this is a n00b question -- I've never written an XSD before.

My initial stab at it is the following:

<xs:element name="business_address" maxOccurs="1">
  <!-- address fields go here -->
  <xs:element name="business_address_state" type="state" maxOccurs="1"></xs:element>
</xs:element>
+2  A: 

I think you are on the right tracks. I think its more to do with XML namespaces. Try the following:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.example.org/foo"
    xmlns:tns="http://www.example.org/foo"
    elementFormDefault="qualified">
    <xs:element name="business_address">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="business_address_state"
                    type="tns:state" maxOccurs="1" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:simpleType name="state">
        <xs:restriction base="xs:string">
            <xs:enumeration value="AL" />
            <xs:enumeration value="AK" />
            <xs:enumeration value="AS" />
            <xs:enumeration value="WY" />
        </xs:restriction>
    </xs:simpleType>
</xs:schema>

Note that the type is tns:state not just state

And then this is how you would use it:

<?xml version="1.0" encoding="UTF-8"?>
<business_address xmlns="http://www.example.org/foo"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.example.org/foo foo.xsd ">
    <business_address_state>AL</business_address_state>
</business_address>

Notice that this XML uses a default namespace the same as the targetNamespace of the XSD

toolkit
After reading up on it, I don't think I need to add the namespace-related attributes. This app will run in an isolated environment. Is it bad form to leave it out?
Huuuze
You don't necessarily need namespace prefixes if you use the default namespace in your XML instance. See my example above.
toolkit
+2  A: 
6eorge Jetson