How to disable/avoid Ampersand-Escaping in Java-XML?

oleh picture oleh · Sep 19, 2011 · Viewed 8.9k times · Source

I want to create a XML where blanks are replaced by  . But the Java-Transformer escapes the Ampersand, so that the output is  

Here is my sample code:

public class Test {

    public static void main(String[] args) {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();

        Element element = document.createElement("element");
        element.setTextContent(" ");
        document.appendChild(element);

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult streamResult = new StreamResult(stream);
        transformer.transform(new DOMSource(document), streamResult);
        System.out.println(stream.toString());

    }

}

And this is the output of my sample code:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<element>&amp;#160;</element>

Any ideas to fix or avoid that? thanks a lot!

Answer

Łukasz Woźniczka picture Łukasz Woźniczka · Jan 11, 2017

The solution is very funny:

Node disableEscaping = document.createProcessingInstruction(StreamResult.PI_DISABLE_OUTPUT_ESCAPING, "&");
 Element element = document.createElement("element");
 element.setTextContent("&#160;");
 document.appendChild(disableEscaping );
 document.appendChild(element);
Node enableEscaping = document.createProcessingInstruction(StreamResult.PI_ENABLE_OUTPUT_ESCAPING, "&");
document.appendChild(enableEscaping )

So basically you need put your code between escaping element.