[xquery-talk] Top N Most Common Mistakes

David Sewell dsewell at virginia.edu
Thu Aug 2 12:49:09 PDT 2007


There is also a common beginner's mistake deriving from a
misunderstanding of how variables work in XPath constructions. One's
instinct is to try this:

  let $xml := <foo><bar>text</bar><baz>text</baz></foo>
  for $el in ("bar", "baz")
  return $xml/$el/text()

when what they want is

  let $xml := <foo><bar>text</bar><baz>text</baz></foo>
  for $el in ("bar", "baz")
  return $xml/*[name(.) eq $el]/text()

What they're not realizing is that in the first case the variable is
being inserted in the XPath expression as a string literal rather than
as the name of an element, so they get a run-time error as a string
literal is not allowed as an intermediate step in an XPath expression.

DS

On Thu, 2 Aug 2007, Torsten Grust wrote:

> Don,
>
> consider the following XQuery expression:
>
> 	let $x := <x/> return $x is $x
>
> which will return return true (`is' test for identical nodes).
> Textual substitution of <x/> for all occurrences of $x leads
> to
> 	<x/> is <x/>
>
> which will return false (the two constructors construct two
> distinct element nodes).  Referential transparency is lost
> (we cannot replace $x with its value without changing the
> meaning of the expression), the FP guys would say.
>
> There are other issues (scoping, for example) which make plain
> textual substitution of variables invalid -- concepts like bound
> and free variables come into play, then.
> Cheers,
>   --Torsten
>
> On Aug 2, 2007 at 16:40, Smith, Donald T. wrote with possible deletions:
> > > You still get the people who imagine that because variables are
> > flagged
> > > with a "$" sign they must work by textual substitution.
> >
> > I don't have the CS background to quite understand how variables work
> > via textual substitution and how they work some other way. I do know --
> > from reading Michael Kay's books -- that XSLT is a functional language
> > and that variables in XSLT can't be updated. I do understand quite well
> > template-based processing and recursive templates.
> >
> > If it's not too much of a digression into CS theory, could someone
> > explain this point?
>
>

-- 
David Sewell, Editorial and Technical Manager
ROTUNDA, The University of Virginia Press
PO Box 801079, Charlottesville, VA 22904-4318 USA
Courier: 310 Old Ivy Way, Suite 302, Charlottesville VA 22903
Email: dsewell at virginia.edu   Tel: +1 434 924 9973
Web: http://rotunda.upress.virginia.edu/


More information about the talk mailing list