Grouping properties using JAXB annotations

I have a Product class with the following properties: name , dateCreated , createdByUser , dateModified and modifiedByUser , and I use JAXB sorting. I would like to have this conclusion:

 <product> <name>...</name> <auditInfo> <dateCreated>...</dateCreated> <createdByUser>...</createdByUser> <dateModified>...</dateModified> <modifiedByUser>...</modifiedByUser> </auditInfo> </product> 

but ideally, I would not want to create a separate AuditInfo wrapper AuditInfo around these properties.

Is there a way to do this using JAXB annotations? I looked at @XmlElementWrapper , but only for collections.

+4
source share
2 answers

No, I do not believe. An intermediate class is required.

You can get around this by specifying AuditInfo as a nested inner class inside Product , and add the getter and setter methods to Product that set the fields in AuditInfo . Product customers never need to know.

 public class Product { private @XmlElement AuditInfo auditInfo = new AuditInfo(); public void setDateCreated(...) { auditInfo.dateCreated = ... } public static class AuditInfo { private @XmlElement String dateCreated; } } 
+2
source

Note. I am the lead EclipseLink JAXB (MOXy) and member of the JAXB 2. X ( JSR-222 ) expert group.

You can use the MOXy @XmlPath for this use case:

 @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Product { private String name; @XmlPath("auditInfo/dateCreated/text()") private Date dateCreated; @XmlPath("auditInfo/createdByUser/text()") private String createdByUser; } 

Additional Information:

+3
source

All Articles