Nested elements with JAXB where the element stores the attribute and value of the element at the same time

Environment: JAXB 2.1.2 with EclipseLink MOXy

Demand:

I would like to get such XML when sorting:

<?xml version="1.0" encoding="UTF-8"?> <root id="id123"> <email> test@gmail.com </email> <address type="short">...</address> </root> 

I am modeling this with these two classes:

 @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name="root") public class ClassA { @XmlAttribute(name="id") private String id = null; @XmlElement(name="address") private Address addr = new Address(); // and some getters setters } 

and

 @XmlAccessorType(XmlAccessType.FIELD) public class Address { @XmlElement(name="address") private String address = null; @XmlAttribute(name="type") private String type = null; } 

I get this where the address is twice nested:

 <?xml version="1.0" encoding="UTF-8"?> <root id="id123"> <email> test@gmail.com </email> <address type="short"> <address>...</address> </address> </root> 

How to delete one hierarchy?

+4
source share
1 answer

You can use the following @XmlValue :

 @XmlAccessorType(XmlAccessType.FIELD) public class Address { @XmlValue private String address = null; @XmlAttribute(name="type") private String type = null; } 

Additional Information

+7
source

All Articles