我在创建xml文件时遇到问题。我需要在从数据库中检索并存储到节点中的sting中保留换行符。我无法让它发挥作用。我尝试了以下变化。
Element ele = doc.createElement("productDescription");
ele.setTextContent(text); // this drops the newlines.
ele.appendChild(doc.createTextNode(text)); // this drops the newlines.
ele.setTextContent(text.replace("\n", " ")); // this changes all the newlines to the text " "
我正在输出文件。
String QueryResults(String query) {
Document doc = CreateDoc(query);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
try {
docTransformer.transform(source, result);
} catch (TransformerException ex) {
System.out.println("Failed to convert doc to string: " + ex.getMessage());
return null;
}
return sw.toString();
}
输出的样本将是。
<result>
<Orders>
<productName>Widget thingy</productName>
<productDescription>A really cool widget thingy.\nReally, its cool.</productDescription>
</Orders>
</result>
答案 0 :(得分:0)
这样怎么样:
ele.setTextContent(text.replace("\n", System.getProperty("line.separator")));