Dark theme | Light theme

September 22, 2008

Add CDATA section to output with XMLSerializer in Cocoon 2.2

We can use Cocoon to put the contents of XML elements in a CDATA section. To achieve this we must configure the XMLSerializer. In Cocoon 2.2 we add a new bean definition to the file src/main/resources/META-INF/cocoon/spring/block-servlet-service.xml.

<bean name="org.apache.cocoon.serialization.Serializer/cdata-xml" class="org.apache.cocoon.serialization.XMLSerializer"
 scope="prototype" parent="org.apache.cocoon.serialization.AbstractTextSerializer">
 <pipeline:component mime-type="text/xml;charset=utf-8"/>
 <property name="format">
   <prop key="encoding">UTF-8</prop>
   <prop key="cdata-section-elements">contents title</prop>

In line 7 we define the XML elements we want to enclose in CDATA. We can use this serializer in our sitemap.xmap and the contents and title elements will have CDATA sections. Suppose we have the following input.xml file:

 <title>My special title.</title>
 <contents>Simple content with &lt;b&gt;html&lt;/b&gt; code.</contents>
 <field>Another field</field>

When we run it through the following pipeline:

<map:match pattern="output.xml">
 <map:generate src="input.xml"/>
 <map:serialize type="cdata-xml"/>

We get the following output:

<xml version="1.0" encoding="UTF-8"?><root>
 <title><![CDATA[My special title.]]></title>
 <contents><![CDATA[Simple content with <b>html</b> code.]]></contents>
 <field>Another field</field>