Jaxb XmlAccessType: PROPERTY EXAMPLE

I am trying to use jaxb and want to use 'XmlAccessType.PROPERTY' so that jaxb uses getters / seters rather than the variable directly, but gets different errors depending on what I am trying, or the variable is not set at all as I want.

Any good link or pointer to a simple example?

For example, the following makes groupDefintion not for installation when parsing an XML document:

@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; } } 
+2
source share
1 answer

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(); } } 
+3
source

Source: https://habr.com/ru/post/1499767/


All Articles