Recipe1.10.Exploiting XPath 2.0 s Extended Type System


Recipe 1.10. Exploiting XPath 2.0's Extended Type System

Problem

You use XML Schema religiously when processing XML and would like to reap its rewards.

Solution

If you validate your documents against a schema, the resulting nodes become annotated with type information. You can then test for these types in XPath 2.0 (and while matching templates in XSLT 2.0).

 (: Test if all invoiceDate elements have been validated as dates. :) if (order/invoiceDate instance of element(*, xs:date)) then "invoicing  complete" else " invoicing incomplete"

instance of is only useful in the presence of schema validation. In addition, it is not the same as castable as. For instance, 10 castable as xs:positiveInteger is always true but 10 instance of xs:positiveInteger is never true because literal integer types are labeled as xs:decimal.


However, the benefit of validation is not simply the ability to test types using instance of but rather from the safety and convenience of knowing that there will be no type error surprises once validation is passed. This can lead to more concise stylesheets.

 (: Without validation, you should code like this. :) for $order in Order return xs:date($order/invoiceDate)  - xs:date($order/createDate) (: If you know all date elements have been validated, you can dispense with  the xs:date constructor.  for $order in Order return $order/invoiceDate - $order/createDate

Discussion

My personal preference is to use XML Schemas as specification documents and not validation tools. Therefore, I tend to write XSLT transformations in ways that are resilient to type errors and use explicit conversions where needed. Stylesheets written in this manner will work in the presence of validation or not.

Once you begin to write stylesheets that depend on validation, you are locked into implementations that perform validation. On the other hand, if your company standards say all XML documents will be schema-validated before processing, then you can simplify your XSLT based on assurances that certain data types will appear in certain situations.




XSLT Cookbook
XSLT Cookbook: Solutions and Examples for XML and XSLT Developers, 2nd Edition
ISBN: 0596009747
EAN: 2147483647
Year: 2003
Pages: 208
Authors: Sal Mangano

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net