Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
GrahamS Avatar asked Nov 26 '25 00:11

GrahamS


1 Answers

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>
like image 101
GrahamS Avatar answered Nov 27 '25 15:11

GrahamS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!