0

I've a function which takes a XML document as parameter and writes it to the file. It contains element as <tag>"some text & some text": <text> text</tag> but in output file it's written as <tag>"some text &amp; some text": &lt;text&gt; text</tag> But I don't want string to be escaped while writing to the file.

Function is,

public static void function(Document doc, String fileUri, String randomId){
    DOMSource source = new DOMSource(doc,ApplicationConstants.ENC_UTF_8);
    FileWriterWithEncoding writer = null;
    try {
        File file = new File(fileUri+File.separator+randomId+".xml");
        if (!new File(fileUri).exists()){
            new File(fileUri).mkdirs();
        }
        writer = new FileWriterWithEncoding(new File(file.toString()),ApplicationConstants.ENC_UTF_8);
        StreamResult result = new StreamResult(writer);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = null;
        transformer = transformerFactory.newTransformer();
        transformer.setParameter(OutputKeys.INDENT, "yes");
        transformer.transform(source, result);
        writer.close();
        transformer.clearParameters();
    }catch (IOException | TransformerException e) {
        log.error("convert Exception is :"+ e);
    }
}
Rajeev
  • 113
  • 1
  • 2
  • 17
  • Do you realize that, if you could do what you asked, your output would no longer be XML, and can no longer be read back by an XML parser? Is that what you want? If so, why? – Erwin Bolwidt Apr 04 '18 at 07:18
  • I only want the text of the element not to be unescaped – Rajeev Apr 04 '18 at 07:49

1 Answers1

1

There are five escape characters in XML ("'<>&). According to XML grammar, they must be escaped in certain places in XML, please see this question:

What characters do I need to escape in XML documents?

So you can't to much, for instance, to avoid escaping & or < in text content.

You could use CDATA sections if you want to retain "unescaped" content. Please see this question:

Add CDATA to an xml file

lexicore
  • 42,748
  • 17
  • 132
  • 221