Because I spended a few hours for that, I decided to write a small blog post about that. The challenge was to create a JAXB implementation independent solution for writing CDATA sections with a JAXB marshaller. There are a lot of solutions out there but they are not satisfying me. A lot of them reference the MOXy CDATA annotation or using the Apache XMLSerializer. They are either not implementation independent, does not work, reference deprecated code or have other pitfalls. The following solution fixes these by using a custom implementation of javax.xml.stream.XMLStreamWriter and has not 3rd party library dependencies. Only the classes of the Java 6 JDK are used. The solution is able to create the following xml:
<test xmlns="http://www.example.org/test" msg="foo"> <text><![CDATA[<o>]]></text> <text>foo</text> </test>
