Home > Articles > Web Services > XML

  • Print
  • + Share This
From the author of

Using Regular Expressions to Add Restrictions to the Schema

Suppose you want to define the schema more precisely. You could add a restriction to the CustomerID, for example, using a regular expression that limits CustomerIDs to exactly five uppercase alphabetic characters. You can do this by modifying the XSD file as shown in Listing 4.

Listing 4 Regular expressions can restrict the XML schema.

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xs:element name="Root">
    <xs:element maxOccurs="unbounded" name="Customer">
      <xs:sequence minOccurs="0">
       <xs:element name="CustomerID" type="valid-customer-id"/>
       <xs:element name="CompanyName" type="xs:string" />
       <xs:element name="ContactName" type="xs:string" />
       <xs:element name="ContactTitle" type="xs:string" />
       <xs:element name="Address" type="xs:string" />
       <xs:element name="City" type="xs:string" />
       <xs:element name="Region" type="xs:string" />
       <xs:element name="PostalCode" type="xs:string" />
       <xs:element name="Country" type="xs:string" />
       <xs:element name="Phone" type="xs:string" />
       <xs:element name="Fax" type="xs:string" />
 <xs:simpleType name="valid-customer-id">
  <xs:restriction base="xs:string">
   <xs:pattern value="^[A-Z]{3}$" />

The change is effected by changing the type of the CustomerID element to the user-defined type valid-customer-id and then defining the new type valid-customer-id as a simple type using a restriction and a regular expressions pattern. (The pattern is shown in boldface near the end of the revised XML schema.)

Next, if you associate the XML schema document with the XML file, Visual Studio will tell you if the source XML violates the schema. In Listing 4, the regular expression ^[A-Z]{3}$ restricts the ID to exactly three uppercase alphabetic characters, which is intentionally wrong to illustrate how the schema describes and enforces that the XML match the schema.

To associate the XSD file with the XML file, follow these steps:

  1. Open the Solution Explorer.
  2. Select the XML file and press F4 to open the properties window.
  3. Use the browser to change the Schema property to refer to the XSD file, as shown in Figure 4.
  4. Finally, open the XML file to see that the XSD restriction has caught the invalid customer IDs (see Figure 5).
Figure 4

Figure 4 Associate the schema file with the XML file to restrict the XML data.

Figure 5

Figure 5 Visual Studio indicates that the CustomerIDs are not matching the restriction in the associated XSD file.

When you're finished looking at the relationship between the XML and XSD files and how Visual Studio reports the failed restriction, you can change the length of the regular expression to 5.

  • + Share This
  • 🔖 Save To Your Account