Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use or implement arrays in XQuery?

Is there any built in support for array in XQuery? For example, if we want to implement the simple java program in xquery how we would do it:

(I am not asking to translate the entire program into xquery, but just asking how to implement the array in line number 2 of the below code to xquery? I am using marklogic / xdmp functions also).

java.lang.String test = new String("Hello XQuery");
char[] characters = test.toCharArray();

for(int i = 0; i<characters.length; i++) {
    if(character[i] == (char)13) { 
        character[i] = (char) 0x00;
    }
}

Legend:

hex 0x00 dec 0 : null
hex 0x0d dec 13: carriage return
hex 0x0a dec 10: line feed
hex 0x20 dec 22: dquote
like image 457
Ranjan Sarma Avatar asked Dec 20 '22 12:12

Ranjan Sarma


2 Answers

The problem with converting your sample code to XQuery is not the absence of support for arrays, but the fact that x00 is not a valid character in XML. If it weren't for this problem, you could express your query with the simple function call:

translate($input, '&#x13;', '&#x00;')

Now, you could argue that's cheating, it just happens so that there's a function that does exactly what you are trying to do by hand. But if this function didn't exist, you could program it in XQuery: there are sufficient primitives available for strings to allow you to manipulate them any way you want. If you need to (and it's rarely necessary) you can convert a string to a sequence of integers using the function string-to-codepoints(), and then take advantage of all the XQuery facilities for manipulating sequences.

The lesson is, when you use a declarative language like XQuery or XSLT, don't try to use the same low-level programming techniques you were forced to use in more primitive languages. There's usually a much more direct way of expressing the problem.

like image 102
Michael Kay Avatar answered Dec 30 '22 22:12

Michael Kay


XQuery has built-in support for sequences. The function tokenize() (as suggested by @harish.ray) returns a sequence. You can also construct one yourself using braces and commas:

let $mysequence = (1, 2, 3, 4)

Sequences are ordered lists, so you can rely on that. That is slightly different from a node-set returned from an XPath, those usually are document-ordered.

On a side mark: actually, everything in XQuery is either a node-set or a sequence. Even if a function is declared to return one string or int, you can treat that returned value as if it is a sequence of one item. No explicit casting is necessary, for which there are no constructs in XQuery anyhow. Functions like fn:exists() and fn:empty() always work.

HTH!

like image 28
grtjn Avatar answered Dec 30 '22 21:12

grtjn