XMLStreamWriter writeCharacters没有转义 [英] XMLStreamWriter writeCharacters without escaping
问题描述
如何使用XMLStreamWriter准确写出我输入的内容?例如,如果我创建脚本标记并用javascript填充它我不希望我的所有单引号都出现为&
How do I use XMLStreamWriter to write exactly what I put in? For instance, if I create script tag and fill it with javascript I don't want all my single quotes coming out as '
这是我写的一个小测试我没有使用任何抽象,只需要调用writeCharacters。
Here's a small test I wrote that doesn't use any of the abstractions I've got in place, just calls to writeCharacters.
public void testWriteCharacters() {
StringWriter sw = new StringWriter();
XMLOutputFactory factory = XMLOutputFactory.newInstance();
StringBuffer out = new StringBuffer();
try {
XMLStreamWriter writer = factory.createXMLStreamWriter(sw);
writer.writeStartElement("script");
writer.writeAttribute("type","text/javascript");
writer.writeCharacters("function hw(){ \n"+
"\t alert('hello world');\n" +
"}\n");
writer.writeEndElement();
out.append(sw);
} catch (XMLStreamException e) {
} finally {
try {
sw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
System.out.println(out.toString());
}
这会为hello world周围的单引号生成一个实体。
This produces an apos entity for both the single quotes surrounding hello world.
推荐答案
XmlStreamWriter.writeCharacters()
不会逃避
。它只能逃过<
,>
和&
和 writeAttribute
也转义(参见 javadoc )。
XmlStreamWriter.writeCharacters()
doesn't escape '
. It only escapes <
, >
and &
, and writeAttribute
also escapes "
(see javadoc).
但是,如果你想在没有转义的情况下编写文本,你必须使用 writeCData()$ c $将其写成
CDATA
部分。 c>。
However, if you want to write text without escaping at all, you have to write it as a CDATA
section using writeCData()
.
在 CDATA
部分编写脚本的典型方法是:
The typical approach for writing scripts in CDATA
sections is:
<script>//<![CDATA[
...
//]]></script>
即:
out.writeCharacters("//");
out.writeCData("\n ... \n//");
这篇关于XMLStreamWriter writeCharacters没有转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!