Search code examples
xmlxsdip-address

How do I represent an IP address in an XML Schema Definition?


I would like to define a type in my XML Schema Definition (XSD) that represents an IPv4 address in dot-decimal notation, so that in my XML:

<Example>
    <Address>192.168.0.1</Address>
</Example>

will be validated as correct and incorrect values such as:

<Example>
    <Address>192.268.0.1</Address>
</Example>

are rejected as invalid.


Solution

  • Solution

    Use the following type definition in your XSD file:

    <xs:simpleType name="IPv4Address">
      <xs:annotation>
        <xs:documentation>IPv4 address in dot-decimal notation. Equivalent to [0-255].[0-255].[0-255].[0-255]</xs:documentation>
      </xs:annotation>
      <xs:restriction base="xs:string">
        <xs:pattern value="((1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" />
      </xs:restriction>
    </xs:simpleType>
    

    This will only accept values 0 to 255 in each of the four dot-separated fields.

    Explanation of the Pattern

    The pattern is:

    ((1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])
    

    which is just this group clause:

    (1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])
    

    repeated {3} three times with a \. dot after it and then one more time without the dot.

    The | bars break that group clause into three alternative matches:

    1?[0-9]?[0-9] matches all numbers from 0 to 199.
    2[0-4][0-9] matches three digit numbers starting with a 2, from 200 to 249.
    25[0-5] matches 250 to 255

    Example Use in Schema

    Once defined the type can be used in the schema like this:

    <xs:element name="Example">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="Address" maxOccurs="1" type="IPv4Address" />
        </xs:sequence>
      </xs:complexType>
    </xs:element>