XML technologies / XSLT / XSLT Kochbuch / XPath / Making use of the extended type system of XPath 2.0
(Excerpt from "XSLT Kochbuch" by Sal Mangano)
Problem
You make very conscientious use of XML Schema when processing XML and would like to reap the rewards.
Solution
Validating your documents against a schema annotates the resulting nodes with type information. You can then test these types in XPath 2.0 (and when filtering templates in XSLT 2.0 ).
(: Test, ob alle invoiceDate-Elemente tatsächlich als Datum validiert worden sind. :)
if (order/invoiceDate instance of element(*, xs:date)) then "Rechnung vollständig" else "Rechnung unvollständig"
Warning!instance of is only useful with schema validation. It is also not the same as castable as. For example, 10 castable as xs:positiveInteger is always true, whereas 10 instance of xs:positiveInteger is never true because integer literals are identified as xs:decimal.
The advantage of validation is not merely the ability to test types using instance of, but the assurance and convenience of knowing that successful validation leaves no unpleasant surprises from type errors. This can make stylesheets clearer.
(: Ohne Validierung sollten Sie den Code so schreiben. :)
for $order in Order return xs:date($order/invoiceDate) - xs:date($order/createDate)
(: Wenn Sie wissen, dass alle Datumselemente validiert wurden, können Sie ohne den xs:date-Konstruktor fertig werden. :)
for $order in Order return $order/invoiceDate - $order/createDate
Discussion
Personally, I prefer to use XML Schema to specify documents rather than validate them. I therefore usually write XSLT transformations to tolerate type errors, using explicit conversions when needed. Stylesheets written this way work with or without validation.
Once your stylesheets depend on validation, you are tied to implementations that perform it. If your organization requires all XML documents to be schema-validated before processing, however, you can simplify your XSLT by relying on the assurance that certain data types occur in particular situations.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from "XSLT Kochbuch" is subject to the same terms as the printed edition: the work and all its parts are protected by copyright. All rights are reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de