【问题标题】:Correct xml escaping in Java在 Java 中正确的 xml 转义
【发布时间】:2016-09-13 00:23:36
【问题描述】:

我需要将 CSV 转换为 XML,然后再转换为 OutputStream。规则是在我的代码中将" 转换为"

输入 CSV 行:

{"Test":"Value"}

预期输出:

<root>
<child>{&quot;Test&quot;:&quot;Value&quot;}</child>
<root>

当前输出:

<root>
<child>{&amp;quot;Test&amp;quot;:&amp;quot;Value&amp;quot;}</child>
<root>

代码:

File file = new File(FilePath);
BufferedReader reader = null;

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

Document newDoc = domBuilder.newDocument();
Element rootElement = newDoc.createElement("root");
newDoc.appendChild(rootElement);

reader = new BufferedReader(new FileReader(file));
String text = null;

    while ((text = reader.readLine()) != null) {
            Element rowElement = newDoc.createElement("child");
            rootElement.appendChild(rowElement);
            text = StringEscapeUtils.escapeXml(text);
            rowElement.setTextContent(text);
            }

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(newDoc);
Result outputTarget = new StreamResult(outputStream);
TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
System.out.println(new String(baos.toByteArray()))

你能帮忙吗?我想念什么以及何时将&amp;amp; 转换为&amp;amp;

【问题讨论】:

  • 你是双重转义。 DOM 会为你逃跑,但你也逃跑了。删除对StringEscapeUtils.escapeXml(text)的调用。
  • 我已经读过这个。奇怪的是,去掉转义后,根本没有转义发生。
  • 因为您只需要在带有" 引用的值的属性中转义",例如这是有效的 XML:&lt;test foo="he'd said: &amp;quot;Hello&amp;quot;" bar='he&amp;apos;d said: "Hello"'&gt;he'd said: "Hello"&lt;/test&gt;。字符&lt;&amp;amp; 必须始终被引用(CDATA 中除外),而&gt; 仅在跟随]] 时才需要引用(如在CDATA 终止符]]&gt; 中),但&gt; 通常总是被引用也是。

标签: java xml stringescapeutils


【解决方案1】:

XML 库会自动转义需要进行 XML 转义的字符串,因此您无需使用 StringEscapeUtils.escapeXml 手动转义。只需删除该行,您就会得到正是您要查找的内容正确转义的 XML。

XML 不要求 " 字符在任何地方都被转义,仅在属性值内。所以这已经是有效的 XML:

<root>
<child>{"Test":"Value"}</child>
<root>

如果您有一个包含引号的属性,您将转义引号,例如:&lt;child attr="properly &amp;quot;ed"/&gt;

这是使用 XML 库的主要原因之一:引用的微妙之处已经为您处理好了。无需阅读XML spec 以确保您得到正确的引用规则。

【讨论】:

  • 我已经读过这个。奇怪的是,去掉转义后,根本没有转义发生。
  • @user3305630:根据您的评论更新了答案
猜你喜欢
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 2012-11-06
  • 2014-04-27
  • 1970-01-01
  • 2012-08-30
  • 2011-05-31
  • 1970-01-01
相关资源
最近更新 更多