Castor and marshalling of CDATA

by Easy Writer - 2004-06-21 @ 01:48

Actually, marshalling of text containing "illegal" XML-characters, such as "<" and "&" is quite easy. I myself wasn't able to find an example, which is why I wrote this page.

The example shouldn't need much explanation (if you've read the ordinary Castor guide at castor.org), so I'll just show you the code. Furthermore, you are always welcome to send me an electronic letter: henrik (a) webdata .dk

         // Get mapping
            Mapping mapping = new Mapping();
         
         // The file containing the mapping
            String filePath = bundle.getString("config.persistor.mapping");
            mapping.loadMapping(test);
            
         // Create output format
            OutputFormat format = new OutputFormat(Method.XML, "UTF-8", true);
            
         // Define the names of the XML elements to put > around
            String[] cdata = {"contentBefore", "contentAfter", "content"};
            format.setCDataElements(cdata);
            format.setNonEscapingElements(cdata); // Those elements should NOT be escaped..
            
         // Create the serializer
            XMLSerializer serializer = new XMLSerializer(writer, format);
         
         // Create the document handler
            DocumentHandler handler = serializer.asDocumentHandler();
            
         // Create the marshaller
            Marshaller marshaller = new Marshaller(handler);
            marshaller.setMapping(mapping);
         
         // Do it!
            marshaller.marshal(object); // The object you wanna marshal
            writer.flush(); // always flush,
            writer.close(); // and close writers (and readers, input-/outputstreams)
         

The XML structure could ie. look like this:

	   <root>
		<config name="test">
			<contentBefore><![CDATA[This is raw unescaped data: < & >]]></contentBefore>
			<contentAfter><![CDATA[2-3<0]]></contentAfter>
		</config>
		<element config="test">
			<content><![CDATA[boolean success = (love && (income-expenses>0);]]></content>
		</element>
	   </root>