Why are you escaping my angle brackets?

December 10, 2008 Data & AI

In the recent past more than one XQuery user has asked me the same question: why is XQuery escaping my angle brackets? One of the examples of such problem looked something like this:[cc lang="xquery"]let $input :=

book 1 book 2

for $book in $input/book return (string(""), $book/text(), string(""))[/cc]
...and the result is:[cc lang="xquery"] < book_123 >book 1</ book_123 > < book_456 >book 2</ book_456 > [/cc]
Indeed XQuery is escaping (converting the character into entities) those angle brackets; but rightfully so! What the user is trying to do is to output XML elements whose name and value are dynamically computed; but what that XQuery is doing is to output *text*, not elements; that's why escaping is taking place.
What the user is really trying to do is what XQuery supports through computed constructors; computed constructors allow to create elements "dynamically", without any need to worry about angle brackets, escaping or anything like that.
Changing the XQuery to use computed constructors is easy:[cc lang="xquery"] let $input :=

book 1 book 2

for $book in $input/book return element {concat("book_", $book/@isbn)} {$book/text()} [/cc]This time the result of the XQuery is what the user is looking for:[cc lang="xquery"] book 1 book 2 [/cc]
This is just something to remember if you ever hit a similar scenario; as it often happens, if the XQuery you are writing to process or create XML looks too cumbersome, most likely it is!

Minollo