作为特殊要求,我一直在尝试越狱"
与 \"
写作时XML
使用 DOM
.
不幸的是,当我用 Document.createTextNode(TextValue)
写文本时, 它输出 \"
.但是,预期的是 \"
详细信息:
写入文本值:
public static boolean setDOMElementValue(Document doc, Element elem, String nodeValue) {
try {
elem.appendChild(doc.createTextNode(nodeValue));
return true;
} catch (DOMException ex) {
LOG.log(Level.SEVERE, ex.toString());
return false;
}
}
编写 XML:
public static boolean writeDOMToXML(Document doc, String xmlFilePath) {
try {
doc.setXmlStandalone(true);
// write content into xml file
// Creating TransformerFactory and Transformer
Transformer tr = TransformerFactory.newInstance().newTransformer();
// Setting Transformer's output properties
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.STANDALONE, "no");
// Setting DOMSource and StreamResult
DOMSource source = new DOMSource(doc);
File file = new File(xmlFilePath);
StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(file)));
// Transform and Return
tr.transform(source, result);
return true;
} catch (TransformerFactoryConfigurationError | TransformerConfigurationException ex) {
LOG.log(Level.SEVERE, ex.toString());
return false;
} catch (TransformerException | FileNotFoundException ex) {
LOG.log(Level.SEVERE, ex.toString());
return false;
}
}
最佳答案
当您使用 DOM 构建文本节点时,您应该简单地在其中输入任何字符串,例如doc.createTextNode("\"")
。当您序列化 DOM 树时,序列化程序将根据需要转义任何字符(但在文本节点中不需要转义 double 或单精度字符)引号,仅在属性值内部是必需的,具体取决于属性值定界符)。
关于java - 如何在“with\”转义时避免转义 &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19837707/