TransformerHandler to output CDATA sections
I am trying to output CDATA section using the below code. While other declarations are being honoured the CDATA sections still comes out as plain text without its enclosing tags (CDATA). What am i doing wrong?
private TransformerHandler getHandler(StringWriter sw) {
开发者_开发问答 SAXTransformerFactory stf = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
TransformerHandler th = null;
th = stf.newTransformerHandler();
th.getTransformer().setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "{ns1}elem");
th.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
th.getTransformer().setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
th.setResult(new StreamResult(sw));
}
Try re-reading the JavaDoc section for OutputKeys.CDATA_SECTION_ELEMENTS: http://docs.oracle.com/javase/6/docs/api/javax/xml/transform/OutputKeys.html#CDATA_SECTION_ELEMENTS
... as well as the referenced explanation of how to specify a literal QName http://docs.oracle.com/javase/6/docs/api/javax/xml/transform/package-summary.html#qname-delimiter
The parameter value that you specify "{ns1}elem", does NOT look like it includes a namespace URI to me, but rather looks like a namespace prefix (ns1). Find out what the "xmlns:ns1" declaration is, and include the namespace URI in the literal QName.
Example (assuming the namespace declaration for the ns1 prefix looks like xmlns:ns1="http://softee.org" you should specify;
setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "{http://softee.org}elem");
精彩评论