1

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);
    }
}
2
  • 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? Commented Apr 4, 2018 at 7:18
  • I only want the text of the element not to be unescaped Commented Apr 4, 2018 at 7:49

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I cannot modify the content of XML

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.