Thursday, June 7, 2007

XPath: Debugging with trace()

Scroll with trace() outputXPath is designed to be used within a host language, like XSLT or XForms. Some host languages provide a tracing facility: for instance XSLT has the <xsl:message> construct. Other host languages however don't, like XForms. For this reason the XPath trace() function can be quite useful1. trace() takes 2 arguments: a value which is a sequence of items, and a label which is a string. It returns the value and logs both the label and value in an implementation dependent way. Let's see what is logged when you execute the following XPath expressions with the open source Saxon engine on the employees document we have seen before:
  • The expression: trace(/company/employee[1]/@firstname, 'Name')
    Shows: Name [1]: attribute(firstname, untypedAtomic): /company/employee[1]/@firstname
  • The expression: trace(string(/company/employee[1]/@firstname), 'Name')
    Shows: Name: xs:string: John
  • The expression: trace(/company/employee, 'Employee')
    Shows: Employee [1]: element(employee, untyped): /company/employee[1] Employee [2]: element(employee, untyped): /company/employee[2] Employee [3]: element(employee, untyped): /company/employee[3]
  • The expression: trace(/, 'Document node')
    Shows: Document node: document-node(): /
When you use trace() in an expression, there is no guarantee that the function will be executed, as the engine might not need to run that part of the expression, which mean that you might not see anything in the trace output. The following expression reads "false() and ...". This is an and expression which starts with false(), so whatever comes after that doesn't matter: the result is always false(). In cases like this, the XPath engine is likely not to run the trace() function call. false() and trace(true(), 'This doesn''t get displayed') You can see what an expression returns by putting the whole expression inside a trace(), like in the examples above. You can also use it inside a path expression. For instance this returns a sequence of names: /company/employee/string(@firstname) To see what are the employees taken into consideration by this expression, just add a trace() step within the path expression: /company/employee/trace(., 'Employee')/string(@firstname)

1 trace() is an XPath 2.0 function. XForms 1.0 uses XPath 1.0, so unfortunately you can't use trace() in XForms, unless your XForms engine specifically supports XPath 2.0, like Orbeon Forms.

No comments:

Post a Comment