What is the Jaxb equivalent of a Text node value?
Asked Answered
C

4

18

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>.

Clary answered 30/9, 2009 at 3:57 Comment(1)
As many have mentioned, the title of this question was misleading as it asks for how to render CDATA blocks but the example above does not illustrate this clearly. At the time I posted I didn't need a CDATA block but just needed to know about the @XmlValue annotation. This is why I awarded the answer to jarnbjo. Since that time, I did indeed need information on how to produce a CDATA block; so subsequent answers were also very helpful. I've voted up each. Thanks for the help everyone!Clary
B
30

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

Baer answered 30/9, 2009 at 8:43 Comment(0)
F
4

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:

Fachan answered 15/7, 2010 at 0:12 Comment(2)
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.Fachan
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.Clary
P
1

This documentation writes:

Q. How can I cause the Marshaller to generate CDATA blocks?

A. This functionality is not available from JAXB directly, but you can configure an Apache Xerces-J XMLSerializer to produce CDATA blocks. Please review the JaxbCDATASample.java sample app for more detail.

(btw, this does not answer your particular question, but since the question title is misleading, and this is the first google result for jaxb CDATA, I'm answering a bit different question)

Presuppose answered 4/2, 2011 at 13:7 Comment(0)
A
0

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

Attractant answered 13/7, 2010 at 5:21 Comment(1)
The JAXB spec does not cover CDATA, however JAXB implementations such as EclipseLink JAXB (MOXy) do contain extensions for handling CDATA, bdoughan.blogspot.com/2010/07/cdata-cdata-run-run-data-run.htmlFachan

© 2022 - 2024 — McMap. All rights reserved.