2

Can someone guide me to generate XML using Jaxb2Marshaller with special characters e.g. '&', '<', '>'? I have got a few pointers on StackOverflow to use below snippet in spring config file, but the same doesnt work out & I continue to receive '&amp', '&lt', '&gt' respectively. Any pointers will be really helpful.

<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="marshallerProperties">
    <map>
        <entry key="jaxb.encoding">
            <value>UTF-8</value>
        </entry>
    </map>

1 Answers1

0

&<> may not appear inside valid XML. they must be either changed to named entities (&<>) or present inside CDATA block. Sample you provided

<name> Test & Value </name>

Is not valid XML! It must be either

<name> Test &amp; Value </name>
or
<name><![CDATA[Test & Value]]</name>

This answers https://stackoverflow.com/a/4438368/1849837 shows that you could use EclipseLink JAXB (MOXy). It has annotation @XmlCDATA, that you could add to your element.

Community
  • 1
  • 1
Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113
  • Thanks Bartosz! I tried via CDATA using below class (as an adapter to to Jaxb2Marshaller), but it returns encoded data inside CDATA (&amp); how can that be escaped?: `public class StringCustomAdapter extends XmlAdapter { public String unmarshal(String fieldValue) throws Exception { return fieldValue; } public String marshal(String fieldValue) throws Exception { fieldValue = StringEscapeUtils.unescapeXml("<![CDATA[" + fieldValue + "]]>"); return fieldValue; } }` – Aditya Gaurav Jan 06 '16 at 18:33