Java中正确的xml转义

Java中正确的xml转义,java,xml,stringescapeutils,Java,Xml,Stringescapeutils,我需要将CSV转换为XML,然后再转换为OutputStream。规则是在我的代码中将“转换为” 输入CSV行: {"Test":"Value"} 预期产出: <root> <child>{&quot;Test&quot;:&quot;Value&quot;}</child> <root> 你能帮忙吗?我错过了什么以及何时将&转换为&?XML库将自动转义需要XML转义的字符串,因此您不需要使用StringE

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

输入CSV行:

{"Test":"Value"}
预期产出:

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

你能帮忙吗?我错过了什么以及何时将
&
转换为
&

XML库将自动转义需要XML转义的字符串,因此您不需要使用
StringEscapeUtils.escapeXml
手动转义。只需删除这一行,您就应该得到正确转义的XML

XML不需要到处转义
字符,只在属性值内转义。因此,这已经是有效的XML:

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

{“测试”:“值”}

如果您有一个包含引号的属性,例如:
您是双重转义。DOM将为您转义,但您也转义。删除对
StringEscapeUtils.escapeXml(text)的调用
。我已经读到了。奇怪的是,在删除转义后,根本没有转义发生。因为您只需要在属性中转义
,属性值由
引用,例如,这是有效的XML:
他说:“你好”
。字符
只需要在遵循
]
时引用(就像在CDATA终止符
]]>
中一样),但
通常也会被引用。我已经了解到了这一点。奇怪的是,在删除转义后,根本没有转义发生。@user3305630:根据您的评论更新了答案
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()))
<root>
<child>{"Test":"Value"}</child>
<root>