More Schematron Features - Declaring variables with the let element
(Page 3 of 5 )
Another useful and powerful element in Schematron is the let element. Building expressions in Schematron can get complicated, but the let element can, thankfully, make some things easier. It allows named variables to be declared in a schema. Using the let element, the result of an expression can be assigned to a variable, and the variable can then be used in other expressions.
The let element is easy to use. It has two simple attributes. The first attribute is the name attribute, used to declare the variable's name. The second attribute is the value attribute, used to assign a value to the variable using an expression.
Consider an XML element representing an e-mail address. Suppose we want to verify that the domain used in the e-mail address is indeed a valid domain. To do this, we would have to extract the domain from the e-mail address. Then, we'd have to perform a number of tests on the domain, such as checking to see if the domain is of appropriate length, checking to see that the characters are valid, and checking to see that a valid top-level domain is being used. In order to perform all these tests, a lot of assertions would have to be made. These assertions would be easier if the domain name could be stored in a variable rather than having to be extracted in each assertion.
Here's how the domain name could be extracted from an e-mail address contained in an email element using a let element and an XPath expression:
<let name="domain" value="substring-after(email,'@')"/>
The let element above would go at the assertion level, though it is possible to use the let element at different levels in the document.
The domain can now be checked for validity. For example, an entire domain name cannot be longer than 253 characters. The name can easily be checked against this using the variable we just created:
<report test="string-length($domain)>253">The domain is too long.</report>
As you can see, variables declared using let are referenced just as parameters are in an abstract pattern.
Next: Phases >>
More XML Articles
More By Peyton McCullough