|
>Home>Learn XQuery> XQuery Tips and Tricks>Including CDATA in Results
Print
Can I include CDATA sections in my XQuery results?
I have this XQuery:
let $v := "<e/>"
return <e>{ $v }</e>
If I run it, I get the following result:
<e><e/></e>
… but what I really want is a CDATA section as the value of <e> which prevents the need of escaping characters:
<e><![CDATA[<e/>]]></e>
Both results represent the same XML document; CDATA sections are nothing more than syntactical sugar. Neither the XML Info Set nor the XQuery 1.0 Data Model know about the concept of CDATA sections. So what you have here is an <e> element, with a single text node with content <e>.
Someone might be tempted to solve the problem by changing the XQuery to:
let $v := "<e/>"
return <e>{ fn:concat("<![CDATA[", $v, "]]>") }</e>
… but that won’t help much, as the result becomes:
<e><![CDATA[<e/>]]></e>
DataDirect XQuery™ allows you to control the serialization parameters through either its XQJ API or through the XQuery itself. One of these serialization parameters (cdata-section-elements) allows you to specify that the value of the listed elements must be serialized in CDATA sections, rather than as escaped text. That means I can change the XQuery from which we started to this:
declare option ddtek:serialize "cdata-section-elements=e";
let $v := "<e/>"
return <e>{ $v }</e>
… and I get the output in the format I want:
<e><![CDATA[<e/>]]></e>
More in general, the parameter value of cdata-section-elements is a list of qnames, separated by semi-colons; namespaces can be specified using the well known compact notation by James Clark, "{"+namespace uri+"}"localname.
For example, this XQuery:
declare namespace p1 = "uri1";
declare namespace p2 = "uri2";
declare namespace p3 = "uri3";
declare option ddtek:serialize "indent=yes,cdata-section-elements={uri1}e;e;{uri2}e";
<result>
<e>aaa</e>
<p1:e>bbb</p1:e>
<p2:e>ccc</p2:e>
<p3:e>ddd</p3:e>
</result>
…generates this output:
<result>
<e><![CDATA[aaa]]></e>
<p1:e xmlns:p1="uri1"><![CDATA[bbb]]></p1:e>
<p2:e xmlns:p2="uri2"><![CDATA[ccc]]></p2:e>
<p3:e xmlns:p3="uri3">ddd</p3:e>
</result>
Next Question!
Why do I get the wrong results looking for the my book's first author?
|