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

I want to create XML where spaces are replaced with   . But the Java-Transformer eludes Ampersand, so 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 result of my code:

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

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

+4
source share
4 answers

Set the text content directly to the character you need, and the serializer will select it for you, if necessary:

 element.setTextContent("\u00A0"); 
+5
source

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 to put your code between the escape element.

+1
source

Try using

 element.appendChild (document.createCDATASection ("&#160;")); 

instead

 element.setTextContent(...); 

You will get this in your xml: This may work if I understand correctly what you are trying to do.

0
source

As an addon forty two answers:

If, like me, you try to use the code in an unencrypted Eclipse IDE, you will most likely see something strange appearing instead of inextricable space. This is because the console encoding in Eclipse does not match Unicode (UTF-8).

Adding -Dfile.encoding=UTF-8 to your eclipse.ini should solve this problem.

Cheers, Wim

0
source

All Articles