java - 转义双引号无法正常工作

标签 java unicode character-encoding xml-parsing escaping

我正在用 Java 编写一个解析器,并在 XML dom 中编写一个字符串。

这是我的代码

String val="\""+val+"\"";
String temp=StringEscapeUtils.escapeXml(val);
node.setTextContent(temp);

然后我使用 LSSerializer

DOMImplementationLS domImplementation = (DOMImplementationLS)doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
String tempString=lsSerializer.writeToString(doc);

并保存到文件。

现在我的问题是字符串“test”应该是& quot;test& quot;,但它是& amp;quot ;测试"

似乎 & 是单独转义的。谁能告诉我我的代码出了什么问题吗?

最佳答案

你的字符串被转义了两次。

  1. "test" -> "test"(" 转义为 ")
  2. “test” -> &“test&”(& 转义为 &)

我被欺骗相信这句话

node.setTextContent(temp);

已经进行了转义,但事实并非如此...

Node.setTextContent(String) API doc :

...Similarly, on setting, no parsing is performed either, the input string is taken as pure textual content.

但是,LSSerializer是:

Within the character data of a document (outside of markup), any characters that cannot be represented directly are replaced with character references. Occurrences of '<' and '&' are replaced by the predefined entities < and &. The other predefined entities (>, ', and ") might not be used, except where needed (e.g. using > in cases such as ']]>').

因此,无论哪种情况,都不需要使用 StringEscapeUtils.escapeXml(val); 进行两次转义,您可以省略该行,从而导致:

String val="\""+val+"\"";
node.setTextContent(val);

或者更简单:

node.setTextContent("\""+val+"\"");

或者对我来说可能更好一些(我不喜欢连接字符串):

node.setText(String.format("\"%s\"", val));

但是,我不明白为什么你想要 " 被转义,因为它(在文本节点中)不会破坏 XML 格式...... .

关于java - 转义双引号无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15614636/

相关文章:

Java Graphics2D透明背景

java - stackoverflow 如何影响 mule 中的池化组件?

python - 当存在 unicode 数据时,Json 解码器不一致

java - 滚动后第一个项目消失后,自定义 ListView 崩溃

java - 从多个文件复合的模式生成 JAX-B 类

javascript - 将 emoji javascript unicode 代码转换为 utf-8

excel - Camel - Drools 规则编码

c++ - SQLite 字符转换

html - 如何从动态列表的最后一个元素中删除 html unicode 内容?

python - 如何确保所有字符串文字在 python 中都是 unicode