1

我需要将 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;

4

1 回答 1

1

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

XML 不要求"在任何地方都对字符进行转义,只在属性值中进行转义。所以这已经是有效的 XML:

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

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

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

于 2016-09-13T00:57:36.257 回答