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

后端 未结 4 1041
梦谈多话
梦谈多话 2021-01-05 10:50

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

相关标签:
4条回答
  • 2021-01-05 11:17

    Try to use

    element.appendChild (document.createCDATASection (" "));
    

    instead of

    element.setTextContent(...);
    

    You'll get this in your xml: It may work if I understand correctly what you're trying to do.

    0 讨论(0)
  • 2021-01-05 11:18

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

    element.setTextContent("\u00A0");
    
    0 讨论(0)
  • 2021-01-05 11:24

    The solution is very funny:

    Node disableEscaping = document.createProcessingInstruction(StreamResult.PI_DISABLE_OUTPUT_ESCAPING, "&");
     Element element = document.createElement("element");
     element.setTextContent(" ");
     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.

    0 讨论(0)
  • 2021-01-05 11:24

    As addon to forty-two's answer:

    If, like me, you're trying the code in a non-patched Eclipse IDE, you're likely to see some weird A's appearing instead of the non-breaking space. This is because of the encoding of the console in Eclipse not matching Unicode (UTF-8).

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

    Cheers, Wim

    0 讨论(0)
提交回复
热议问题