Java Reference
In-Depth Information
Restricting Schema Types with Regular Expressions
Problem
You need to represent some basic simple types in your schema, such as a phone number or a
Social Security number, and you want a stronger constraint than xs:string gives.
Solution
Use a regular expression inside a pattern to define your constraint, and enforce it with
<xs:restriction> .
In XML Schema, your elements can be expressed by simple types that are defined as strings,
but wrapped with a restriction element that defines a pattern. The pattern is a regular expres-
sion indicating the range of acceptable values. You can also get help from Schema with other
built-in restriction elements, such as <minLength> and <maxLength> .
Here is an example:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://ns.soacookbook.com/cart"
xmlns:tns="http://ns.soacookbook.com/cart"
elementFormDefault="qualified">
<xs:element name="usPhone" type="tns:USPhoneType" />
<xs:simpleType name="USPhoneType">
<xs:restriction base="xs:string">
<xs:pattern value="\(?\d{3}\)?[ \-\.]?\d{3}[ \-\.]?\d{4}"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
Upon validation of an XML document instance, this will reject values for the domain element
that do not conform to the regular expression.
Here is an XML document instance that passes validation for this constraint:
<?xml version="1.0" encoding="UTF-8"?>
<cart:usPhone xmlns:cart="http://ns.soacookbook.com/cart"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Search WWH ::




Custom Search