bog
bog

Reputation: 1323

XQuery: when to use data() function?

I cannot undeerstand when I should use the data() function. Exemple: $path/@name or $path/data(@name)? Sometimes when I don't put data() I got an error that I can fix only adding it.

Upvotes: 5

Views: 3088

Answers (2)

Michael Kay
Michael Kay

Reputation: 163458

It's very rarely necessary to call data() explicitly. Almost all operations that expect atomic values can be given a node and will atomize it (that is, call data()) implicitly.

There are some exceptions:

  • The effective boolean value of a node-sequence N is not the same as the effective boolean value of data(N). For example, if (@married) tests whether the @married attribute exists, while if (data(@married)) tests whether the typed value of the @married attribute is true.

  • When constructing element content in XQuery, nodes are not implicitly atomized, so <e>{@married}</e> does something different from <e>{data(@married)}</e>

Upvotes: 4

wst
wst

Reputation: 11771

Generally, data() should be used when you want to extract the atomic type of a value stored in XML and defined by a schema. For example, say you have a schema that defines this element as xs:dateTime:

<my-time>2016-01-28T10:30:45.954716-06:00</my-time>

Calling data() on <my-time> will return an xs:dateTime type value.

Most of the time, however, data() will simply behave like string(). I suspect in your code there are times when you are expecting a string but returning an attribute or node. Sometimes that "just works" because of type coercion; other times, it throws an exception. This is will of course be dependent on your code.

Pay close attention to the types of nodes and atomic values in your code, and it should be a little more clear why you are getting these errors. And if what you want is a string, then use string() instead of data().

Upvotes: 4

Related Questions