How to output a CDATA section from a Sax XmlHandler
Asked Answered
E

2

4

This is a followup question of How to encode characters from Oracle to Xml?

In my environment here I use Java to serialize the result set to xml. I have no access to the output stream itself, only to a org.xml.sax.ContentHandler.

When I try to output characters in a CDATA Section:

It happens basically like this:

xmlHandler.startElement(uri, lname, "column", attributes);
String chars = "<![CDATA["+rs.getString(i)+"]]>";
xmlHandler.characters(chars.toCharArray(), 0, chars.length());
xmlHandler.endElement(uri, lname, "column");

I get this:

<column>&lt;![CDATA[33665]]&gt;</column>

But I want this:

<column><![CDATA[33665]]></column>

So how can I output a CDATA section with a Sax ContentHandler?

Entebbe answered 1/10, 2008 at 9:0 Comment(0)
P
5

It is getting escaped because the handler.characters function is designed to escape and the <![CDATA[ part isn't considered part of the value.

You need to use the newly exposed methods in DefaultHandler2 or use the TransformerHandler approach where you can set the output key CDATA_SECTION_ELEMENTS, which takes a whitespace delimited list of tag names that should output sub text sections enclosed in CDATA.

StreamResult streamResult = new StreamResult(out);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "column");
hd.setResult(streamResult);
hd.startDocument();
hd.startElement("","","column",atts);
hd.characters(asdf,0, asdf.length());
hd.endElement("","","column");
hd.endDocument();
Personify answered 1/10, 2008 at 13:36 Comment(1)
What do you mean with "... DefaultHandler2 or use the TransformerHandler", how can I use the DefaultHandler2 methods to output CData tags when I serialize the XML. I am already using the functions document.createCDATASection(...) in my code. Is there any way to output CDATA tags without using the CDATA_SECTION_ELEMENTS property?Gardia
T
3

You should use startCDATA() and endCData() as delimiters, i.e.

xmlHandler.startElement(uri, lname, "column", attributes);
xmlHandler.startCDATA();
String chars = rs.getString(i);
xmlHandler.characters(chars.toCharArray(), 0, chars.length());
xmlHandler.endCDATA();
xmlHandler.endElement(uri, lname, "column");
Trusty answered 29/8, 2010 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.