Dear Castor Users,
I thought i'd publish this hack/solution to an occasionally discussed
problem.
Q: How can you disable output escaping on marshalling to XML? What if your
Java class contains a String with some html in it. When you serialize it
with Castor all the <'s and >'s will be output escaped to < and > and
your html tags won't work....and quite rightly so! Disabling output escaping
may cause you to create invalid XML that could then not be unmarshalled,
which is the raison d'etre of Castor.
In my case i'm dumping to XML then styling with XSLT. I'd like to just store
the chunk of html as-is then copy it as-is into my html output.
It got me thinking...xslt has a disable-output-escaping directive so it had
to be possible.
My answer is to use the org.apache.xml.serializer.ToXMLStream as xslt does.
Something like...
code:
----------------------------------------------------------------------------
----
ToXMLStream xmlStreamer = new ToXMLStream();
xmlStreamer.setWriter(writer);
org.xml.sax.ContentHandler handler = xmlStreamer.asContentHandler();
System.setProperty("org.xml.sax.parser","org.apache.xerces.parsers.SAXParser
");
Marshaller marsh = new Marshaller(handler);
marsh.setValidation(false);
marsh.addProcessingInstruction(Result.PI_DISABLE_OUTPUT_ESCAPING, "");
marsh.setMapping(mapping);
marsh.marshal(anObject);
----------------------------------------------------------------------------
----
then i've created a CDataFieldHandler to wrap any fields I choose in my
mapping file....this means they'll be valid XML
code:
----------------------------------------------------------------------------
----
...CDataFieldHandler extends AbstractFieldHandler{
/**
* uses reflection to retrieve the value then wraps
* it in a CDATA section
*/
public Object getValue(Object object) throws IllegalStateException
{
FieldDescriptor f = getFieldDescriptor();
String fieldName = f.getFieldName();
Object value = null;
try
{
value = PropertyUtils.getProperty(object,fieldName);
}
catch (IllegalAccessException e1)
{
e1.printStackTrace();
}
catch (InvocationTargetException e1)
{
e1.printStackTrace();
}
catch (NoSuchMethodException e1)
{
e1.printStackTrace();
}
if (value==null)
{
value = "";
}
return "<![CDATA[" + value.toString() + "]]>";
}
Regards,
Jeremy
Jeremy Nicholson, Technical Architect
PionLabs, Brighton
-----------------------------------------------------------
If you wish to unsubscribe from this mailing, send mail to
[EMAIL PROTECTED] with a subject of:
unsubscribe castor-user