How to create an xml document on the fly using xquery?
I am using XQuery to convert string like "aaa = 1 & bbb = 2" to xml
<request>
<aaa>1</aaa>
<bbb>2</bbb>
</request>
I tried the following code but failed!
xquery version "1.0" encoding "GBK";
(:: pragma type="xs:anyType" ::)
declare namespace xf = "http://tempuri.org/BNetAP/Xquery/query2xml/";
declare function xf:query2xml($queryStr as xs:string)
as element(*) {
<query-params>
{
for $c in
fn:tokenize($queryStr, "&")
let $myname as xs:string := "{fn:substring-before($c,"=")}"
return
element
{fn:QName("", $myname)}
{"{fn:substring-after($c,"=")}"}
}
</query-params>
};
Error message:
line 15, column 6: "{http://www.w3.org/2004/07/xpath-functions}QName": unknown function (or number of arguments (2) is wrong) BNetAP/Xquery query2xml.xq line 15 1241431186406 397
I have no idea why "QName" is "unknow function" ?!
0
source to share
1 answer
You must use the xs: QName constructor, not fn: QName.
The body of your constructed element looks a little fishy as well:
"{fn:substring-after($c,"=")}"
is actually a match between the string "{fn: substring-after ($ c," and string ")}" so the element's content will just be text "false".
Likewise, the variable $ myname is actually set to false, and so a type checking error will be raised at runtime.
Your function should probably be the following:
declare function xf:query2xml($queryStr as xs:string)
as element(*) {
<query-params>
{
for $c in fn:tokenize($queryStr, "&")
let $myname := fn:substring-before($c,"=")
return
element
{xs:QName("", $myname)}
{fn:substring-after($c,"=")}
}
</query-params>
};
A computed element constructor can also only accept a string for its name, so your return expression can be simplified to simple
return element {$myname} {fn:substring-after($c,"=")}
0
source to share