views:

1220

answers:

4

I am looking to convert a class that looks like this ...

public class Amenity {
   public String id;
   public String value;
}

into the following XML using JaxB annotations:

<amenity id="id-string-here">value-string-here</amenity>

Does anyone know what annotation to use on the value member variable to accomplish this? The closest I've gotten so far is:

@XmlRootElement
public class Amenity {
   @XmlAttribute
   public String id;
   @XmlElement
   public String value;
}

Unfortunately this approach doesn't allow me to specify that the value member variable should not be rendered as its own tag <value></value>.

+3  A: 

I'm not 100% sure about this, but try to use an XmlValue annotation instead of XmlElement.

jarnbjo
+1 that's exactly correct
skaffman
+1  A: 

JAXB does not support marshaling/marshaling to/from CDATA xml types.

Wez
The JAXB spec does not cover CDATA, however JAXB implementations such as EclipseLink JAXB (MOXy) do contain extensions for handling CDATA, http://bdoughan.blogspot.com/2010/07/cdata-cdata-run-run-data-run.html
Blaise Doughan
+1  A: 

It looks like the question was referring to text nodes not CDATA nodes, but here is a link on how EclipseLink JAXB (MOXy) handles CDATA:

Blaise Doughan
Not sure why this answer received a down vote. It was left for the benefit of the people who found the issue based on the title. For what it's worth, I did up vote jarnbjo's @XmlValue answer before leaving my own.
Blaise Doughan
Thanks for the reference. It is pretty amazing that CDATA was not considered as part of the existing spec but I guess that as long as the StringWriters correctly encode inner markup there shouldn't be a need for it.
raiglstorfer