CDATA Sections

A CDATA section is a convenience used in XML documents that allows you to include literal text in element content without having to use < and & entity references to escape less-than and ampersand symbols, respectively. CDATA sections are not a separate kind of node; they are not represented in the XQuery data model at all.

CDATA sections are delimited by <![CDATA[ and ]]>. Example 21-12 shows two h1 elements. The first element has a CDATA section that contains some literal text, including an unescaped ampersand character. It also contains a reference to a <catalog> element that is intended to be taken as a string, not as an XML element in the document. If this text were not enclosed in a CDATA section, the XML element would not be well formed. The second h1 element shown in the example is equivalent, using predefined entities to escape the ampersand and less-than characters.

Example 21-12. Two equivalent h1 elements, one with a CDATA section

<h1><![CDATA[Catalog & Price List from <catalog>]]></h1>
<h1>Catalog &amp; Price List from &lt;catalog></h1>

When your query accesses an XML document that contains a CDATA section, the CDATA section is not retained. If the h1 element in Example 21-12 is queried, its content is Product Catalog & Price List from <catalog>. There is no way for the query processor to know that a CDATA section was used in the input document.

For convenience, CDATA sections can also be specified in a query, in the character data content of an element constructor. Example 21-13 shows a query that uses a CDATA section. All of the text in a CDATA section is taken literally; it is not possible to include enclosed expressions in a CDATA section.

Just as in an XML document, a CDATA section in a query serves as a convenient way to avoid having to escape characters. Including a CDATA section in a query does not result in a CDATA section in the query results. As you can see from Example 21-13, the results of the query (when serialized) contain an escaped ampersand and less-than sign in the element content.

Example 21-13. Query with CDATA section

Query
if (doc("catalog.xml")//product)
then <h1><![CDATA[Catalog & Price List from <catalog>]]></h1>
else <h1>No catalog items to display</h1>
Results
<h1>Catalog &amp; Price List from &lt;catalog></h1>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.152.159