user1452030
user1452030

Reputation: 1021

JAXB - Using @xmlvalue with a token field

This seems like a basic issue, but I'm not able to find the answer elsewhere. Pardon me if it's a repeated post.

Is it possible to have an @XmlValue annotation on a class marked as @XmlAccessorType(XmlAccessType.FIELD)?

I'm trying to parse an XML file with JAXB and while the XML itself is pretty large and has other fields, the problem is specific to this field:

<root>
  ...
  <holiday holidayId="9">Christmas</holiday>
  ...
</root>

The mappings are:

public class Holiday extends Model {
    @XmlAttribute(name="holidayId")
    private String holidayId;
    @XmlValue
    private String holiday;
}

The field is declared as a token type in the XML.

The @XmlValue annotation is giving me an IllegalAnnotationException (if I comment out the @XmlValue and the holiday field, the mappings work fine). Why does this fail? What is the work-around? Please advise.

Upvotes: 0

Views: 649

Answers (1)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

Yes, it should work without problems. I used these classes:

@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement(name = "holiday")
    List<Holiday> holidays;
}

.

@XmlAccessorType(XmlAccessType.FIELD)
public class Holiday {

    @XmlAttribute(name="holidayId")
    private String holidayId;

    @XmlValue
    private String holiday;
}

For me it worked fine. I used your XML example input together with this test code:

JAXBContext context = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
File file = new File("root.xml");
Root root = (Root) unmarshaller.unmarshal(file);

Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);

Upvotes: 0

Related Questions