XMLStreamWriter writeCharacters没有转义 [英] XMLStreamWriter writeCharacters without escaping

查看:579
本文介绍了XMLStreamWriter writeCharacters没有转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用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() 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆