本文介绍了如何从 Sax XmlHandler 输出 CDATA 部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是How to encode character from Oracle toxml?

在我这里的环境中,我使用 Java 将结果集序列化为 xml.我无法访问输出流本身,只能访问 org.xml.sax.ContentHandler.

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.

当我尝试在 CDATA 部分中输出字符时:

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");

我明白了:

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

但我想要这个:

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

那么如何使用 Sax ContentHandler 输出 CDATA 部分?

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

推荐答案

它正在被转义,因为 handler.characters 函数旨在转义而 <![CDATA[ 部分不是被视为价值的一部分.

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

您需要使用 DefaultHandler2 中新公开的方法或使用 TransformerHandler 方法,您可以在其中设置输出键 CDATA_SECTION_ELEMENTS,它需要应输出包含在 CDATA 中的子文本部分的以空格分隔的标记名称列表.

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();

这篇关于如何从 Sax XmlHandler 输出 CDATA 部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 18:46