我正在用 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 ;测试"
似乎 & 是单独转义的。谁能告诉我我的代码出了什么问题吗?
最佳答案
你的字符串被转义了两次。
"test"
->"test"
("
转义为"
)“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/