As a special requirement, I have been trying to escape "
with \"
while writing XML
using DOM
.
Unfortunately, when I write text with Document.createTextNode(TextValue)
, it outputs \"
. 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:
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;
}
}