XML Schema How to Declare Price and Currency

currencyschemaxmlxsd

I'm creating an XML schema that stores information about houses.

I want to store the price and the currency.

It makes sense in my mind to declare this by having the currency as an attribute of the price element.

Also, I want to restrict the values that can be entered as the currency to pounds, euros or dollars.

EG:

<price currency="euros">10000.00</price>

So at the moment I'm declaring this in my XML Schema as:

<!-- House Price, and the currency as an attribute -->
<xs:element name="price">
    <xs:complexType>
        <xs:attribute name="currency">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value="pounds" />
                    <xs:enumeration value="euros" />
                    <xs:enumeration value="dollars" />
                </xs:restriction>
            </xs:simpleType>
        </xs:attribute>
    </xs:complexType>
</xs:element>

The issue that I have with this:

  • I'm not exactly sure if this will restrict the attribute element to pounds, euros or dollars

  • I can't seem to specify a type on the price to a double, as I would like due to the error:

    Element 'price' has both a 'type' attribute and a 'anonymous type' child. Only one of these is allowed for an element.

Should I just keep it simple and declare them as separate elements:

<price>10000.00</price>
<currency>euros</currency>

…or am I on the right path?

Best Answer

Taken from the link posted by Michael Kay and applied to your problem. (Note: Use 'decimal' type instead of 'double' to avoid precision errors.)

<xs:element name="price">
  <xs:complexType>
    <xs:simpleContent>
      <xs:extension base="xs:decimal">
        <xs:attribute name="currency" type="currencyType"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
</xs:element>

<xs:simpleType name="currencyType">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds"/>
    <xs:enumeration value="euros"/>
    <xs:enumeration value="dollars"/>
  </xs:restriction>
</xs:simpleType>

---- Example ----

<price currency="euros">10000.00</price>