Sunday, November 5, 2006

XPath: The Many Faces of a Document

Young Women or Old Hag?From time to time, you will come across a function in XPath that returns an XML document. If you are using XSLT 1.0 or 2.0, XPath 2.0, XQuery, or XForms, you will get to use a mix of instance(), doc(), and document(). Let's start with instance() which you'll find in XForms.

XForms is a technology used to create forms. The data you enter in the form is stored in one or more XML documents, which in the XForms jargon are called XForms instances. Each document in XForms has an id which can be used to retrieve the document. Here an example of a declaration of an XForms instance:

<xforms:instance id="address">
        <street>1 Infinite Loop</street>

Assuming that the document in the instance with id address is also accessible at the URI, consider the following XPath expressions:

  • instance('address')
  • doc('')
  • document('')

All 3 expressions return the same "address" document. You can use first expression with instance() in XForms, the second with doc() wherever you have XPath 2.0 or XQuery expressions, and the third with document() within an XPath expression in XSLT 1.0 or 2.0 stylesheets.

While all 3 return the same "address" document, they don't return the same node of the document: instance() returns the root element, while doc() and document() return the document node. This means that to point to the street element, you will need to write:

  • instance('address')/street
  • doc('')/address/street
  • document('')/address/street

Note how the name of the root element ("address") is used with doc() and document() but not with instance(). Granted: the difference between doc()/document() on one side and instance() on the other side is trivial. But it is surprisingly easy to make a mistake when using all these functions in the same day. So keep it mind: the same document can have many faces depending on which function you use.

No comments:

Post a Comment