Castor: Wrap tags in CDATA when Marshalling

I am using Castor to create an XML File for a client. I am using the Castor Sourcecode Generator for Eclipse to create the Object from an XSD.
Everything worked pretty well so far and the XML Output looked quite well – Besides one thing:
I wanted to have the content of a few tags wrapped in a CDATA tag because these tags could have invalid characters which could create problems for the parser.
After googleing around a bit I have found a few sites which came up with a solution.
e.g.
http://webdata.dk/guides/castor-cdata.html
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5011421

This didn’t work instantly for me, because my XML file does not have an own namespace, but is using defaultnamespace:
xmlns=”http://tempuri.org/XMLSchema.xsd”

That is why I had to modify the solution on the given pages, and use the complete url “http://tempuri.org/XMLSchema.xsd” instead of ns1^.

Here is my code which puts CDATA around the tags, which are defined by the variable cdata:

import org.apache.xml.serialize.Method;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.xml.sax.ContentHandler;


Orders orders = tf.process();
Writer writer = new StringWriter();
// Create output format
OutputFormat format = new OutputFormat(Method.XML, “UTF-8″, true);

// Define the names of the XML elements to put CDATA around
String[] cdata = { “http://tempuri.org/XMLSchema.xsd^Comment”,
“http://tempuri.org/XMLSchema.xsd^FirstName”,
“http://tempuri.org/XMLSchema.xsd^LastName”,
“http://tempuri.org/XMLSchema.xsd^Company1″,
“http://tempuri.org/XMLSchema.xsd^Company2″,
“http://tempuri.org/XMLSchema.xsd^Street”,
“http://tempuri.org/XMLSchema.xsd^ZipCode”,
“http://tempuri.org/XMLSchema.xsd^City”,
“http://tempuri.org/XMLSchema.xsd^Phone1″,
“http://tempuri.org/XMLSchema.xsd^Phone2″,
“http://tempuri.org/XMLSchema.xsd^MobilePhone”,
“http://tempuri.org/XMLSchema.xsd^Fax”,
“http://tempuri.org/XMLSchema.xsd^EMail”,
“http://tempuri.org/XMLSchema.xsd^ProductName” };
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
ContentHandler handler = serializer.asContentHandler();

orders.marshal(handler);
writer.flush();
System.out.println(“xml: ” + writer.toString());
writer.close();

//The rendered Content of orders
StringBuffer sb = new StringBuffer(writer.toString());

Maybe that is helpful for somebody else too.

Dieser Beitrag wurde unter Allgemein, Software-Development veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Hinterlasse eine Antwort