Best way to encode text data for XML in Java? Best way to encode text data for XML in Java? java java

Best way to encode text data for XML in Java?


As others have mentioned, using an XML library is the easiest way. If you do want to escape yourself, you could look into StringEscapeUtils from the Apache Commons Lang library.


Very simply: use an XML library. That way it will actually be right instead of requiring detailed knowledge of bits of the XML spec.


Just use.

<![CDATA[ your text here ]]>

This will allow any characters except the ending

]]>

So you can include characters that would be illegal such as & and >. For example.

<element><![CDATA[ characters such as & and > are allowed ]]></element>

However, attributes will need to be escaped as CDATA blocks can not be used for them.