The answer is that your example is not wrong on its own, but there are several possible pitfalls. You posted the annotation on the setter, not on the recipient. Although the JavaDoc for @XmlAttribute does not impose any restrictions on this, other annotations (e.g. @XmlID) specifically allow you to annotate either the installer or the recipient, but not both.
Note that @XmlAttribute expects an attribute, not an element. Also, since it parses an attribute, it cannot be a complex type. So EGroup could be an enumeration, maybe?
I expanded your example and added a few statements, and it works "on my machine" using the latest version of Java 6.
@XmlRootElement @XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.PROPERTY) public class E { private EGroup groupDefinition; public EGroup getGroupDefinition () { return groupDefinition; } @XmlAttribute public void setGroupDefinition (EGroup g) { groupDefinition = g; } public enum EGroup { SOME, OTHERS, THE_REST } public static void main(String[] args) throws JAXBException { JAXBContext jc = JAXBContext.newInstance(E.class); E eOne = new E(); eOne.setGroupDefinition(EGroup.SOME); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); StringWriter writer = new StringWriter(); m.marshal(eOne, writer); assert writer.toString().equals("<e groupDefinition=\"SOME\"/>"); E eTwo = (E) jc.createUnmarshaller().unmarshal(new StringReader(writer.toString())); assert eOne.getGroupDefinition() == eTwo.getGroupDefinition(); } }
source share