[英]How to avoid escaping & while escaping " with \"
As a special requirement, I have been trying to escape "
with \\"
while writing XML
using DOM
. 作为一项特殊要求,我一直试图在使用
DOM
编写XML
"
使用\\"
。
Unfortunately, when I write text with Document.createTextNode(TextValue)
, it outputs \\"
不幸的是,当我用
Document.createTextNode(TextValue)
编写文本时,它会输出\\"
. 。 However, the expected is
\\"
但是,预期的是
\\"
Details: 细节:
Writing Text Value: 写文本值:
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;
}
}
Writing XML: 编写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树时,序列化程序将根据需要处理任何字符(但是在文本节点内,不需要转义双引号或单引号,这只需要在属性值内,具体取决于属性值分隔符)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.