Search code examples
javaxmlxquerymarklogic

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

Solution

  • 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.