ZVON > Tutorials > XML Schema and Relax NG Tutorial
Index | >> Example 4 / 8 << | Prev | Next |
Contents > Definition of own types > Limiting both the number of decimal places and total places

Limiting both the number of decimal places and total places

  1. XML Schema
  2. Relax NG
XML Schema keys: decimal, totalDigits, fractionDigits

1. XML Schema

The element "A" represents a number in the format xxx.xx or -xxx.xx. It must have max. two decimal places and must have 5 total digits. We will define our custom type "myNumber" using "totalDigits" and "fractionDigits" elements. The element "A" must be of that type.

Valid document


<A xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >999.99</A>

Valid document


<A xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >-123.50</A>

Invalid document
There are too many both total and decimal places.


<A xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >9999.9999</A>

Invalid document
The number of decimal places is too high (must be less or equal to 2).


<A xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >99.999</A>

Correct XML Schema (correct_0.xsd)


<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >

  <xsd:element name="A" type="myNumber"/>

  <xsd:simpleType name="myNumber">
    <xsd:restriction base="xsd:decimal">
      <xsd:totalDigits value="5"/>
      <xsd:fractionDigits value="2"/>
    </xsd:restriction>
  </xsd:simpleType>
</xsd:schema>

2. Relax NG

The element "A" represents a number in the format xxx.xx or -xxx.xx. It must it must have two decimal places and must have 5 total digits. We will use the "decimal" datatype from XML Schemas and restrict it using using "totalDigits" and "fractionDigits". The element "A" must contain this pattern.

Valid document


<A xmlns="">999.99</A>

Valid document


<A xmlns="">-123.50</A>

Invalid document
There are too many both total and decimal places.


<A xmlns="">9999.9999</A>

Invalid document
The number of decimal places is too high (must be less or equal to 2).


<A xmlns="">99.999</A>

Correct Relax NG schema (correctRelax_0.rng)


<grammar datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes" xmlns="http://relaxng.org/ns/structure/1.0" >

  <start>
    <element>
      <name ns="">A</name>
      <ref name="myNumber"/>
    </element>
  </start>

  <define name="myNumber">
    <data type="decimal">
      <param name="totalDigits">5</param>
      <param name="fractionDigits">2</param>
    </data>
  </define>
</grammar>