Search code examples
jaxbxml-serializationjaxb2unmarshalling

Unmarhshalling a tricky CDATA element using JAXB


I want to use JAXB to unmarshal the following into a 'Tag' object. This is how the client passes the results to me -

<Tag type="a">
    <![CDATA[html text here]]>
</Tag>

Note that CDATA is wrapped directly inside 'Tag' which has an attribute 'type' to it.

My class is as follows:

@XmlRootElement(name = "Tag")
public class Tag {

private String type;
private String tag;

public String getTag() {
    return tag;
}

@XmlCDATA
public void setTag(String tag) {
    this.tag = tag;
}

public String getType() {
    return type;
}

@XmlAttribute
public void setType(String type) {
    this.type = type;
}

}

I dont think this is the right way, and as expected when I unmarshall, the Tag object is populated with 'type' but the CDATA value does not get populated into 'tag'.

Any idea?


Solution

  • You can add the @XmlValue annotation to the tag property.