In my last two articles, I covered the basics of Schematron—enough of it to create a basic schema with assertions, rules and patterns. However, there is more to Schematron than was covered in those articles, and some of Schematron's other features are very useful and worth mentioning. In this article, we'll take a look at more of Schematron's features, delving deeper into the Schematron schema language.
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: