Tuesday, June 9, 2015

CDATA extension in XML feed with annotation

If you use javax to generate XML content, sometimes you use special characters. Better to place this data into <![CDATA[ ... ]]> tags.


Using annotations are very comfortable.

  1.  Create an adapter class: AdapterCDATA
  2. Add @XmlJavaTypeAdapter annotation to the field

Create the adapter class

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class AdapterCDATA extends XmlAdapter<String, String> {

@Override
public String marshal(String arg0) throws Exception {
return "<![CDATA[" + arg0 + "]]>";
}

@Override
public String unmarshal(String arg0) throws Exception {
return arg0;
}
}

Add the annotation

@XmlRootElement(name = "PressReleaseLinguistic")
@XmlAccessorType(XmlAccessType.FIELD)
public class PressReleaseLinguisticXmlVO implements Serializable {

private static final long serialVersionUID = 3000191037371295127L;

@XmlElement(name = "pdf")
public String pdf;

@XmlJavaTypeAdapter(AdapterCDATA.class)
@XmlElement(name = "html")
private String html;
.....

The result

<PressReleaseLinguistic>
<html>
<![CDATA[<p class="A__35__20_Normal_P5">News from the European Commission"s Midday Briefing</p>]]>
</html>
<language>EN</language>
<title>Sample title</title>
....

No comments:

Post a Comment