views:

1693

answers:

3

I would like to convert a string into a node. I have a method that is defined to take a node, but the value I have is a string (it is hard coded). How do I turn that string into a node?

So, given an XQuery method:

define function foo($bar as node()*) as node() {
  (: unimportant details :)
}

I have a string that I want to pass to the foo method. How do I convert the string to a node so that the method will accept the string.

A: 

MarkLogic solutions:

The best way to convert a string into a node is to use:

xdmp:unquote($string).

Conversely if you want to convert a node into a string you would use:

xdmp:quote($node).

Language agnostic solutions:

Node to string is:

fn:string($node)
Sixty4Bit
xdmp:unquote and quote aren't part of the XQuery language spec, it is part of a set of MarkLogic extension libraries. Loading xml from string literals into a node depends on the XQuery engine being used. http://www.xml.com/lpt/a/1660
Jim Burger
Also, you're node to string code probably doesn't do what the poster wants - it will only return the concatenated string value of all nodes below $node, but not the actual XML syntax (<foo/>)
Martin Probst
:) He *is* the poster
Jim Burger
I hate to accept my own answer, but this is what I was looking for and solved the problem I was having. Does the question need to be restated?
Sixty4Bit
+1  A: 

The answer to this question depends on what engine is being used. For instance, users of Saxon, use the saxon:parse method.

The fact is the XQuery spec doesn't have a built in for this.

Generally speaking you would only really need to use this if you needed to pull some embedded XML from a CDATA section. Otherwise you can read files in from the filesystem, or declare XML directly inline.

For the most you would use the declarative form, instead of a hardcoded string e.g. (using Stylus studio)

declare namespace my = "http://tempuri.org";

declare function my:foo($bar as node()*) as node() {
    <unimportant></unimportant>
} ;

let $bar := <node><child></child></node>

return my:foo(bar)
Jim Burger
+1  A: 

If you want to create a text node out of the string, just use a text node constructor:

text { "your string goes here" }

or if you prefer to create an element with the string content, you can construct an element something like this:

element (some-element) { "your string goes here" }