I'm trying to use jaxb an开发者_如何学Pythond want to use the 'XmlAccessType.PROPERTY' to let jaxb use getters/setters rather than variable directly, but get different errors depending on what I try, or the variable isn't set at all like I want.
Any good link or pointer to a simple example?
For example, the below makes the groupDefintion not to be set when parsing the 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;
}
}
The answer is that your example is not wrong per se, but there are a few possible pitfalls. You have put the annotation on the setter, not the getter. While the JavaDoc for @XmlAttribute does not state any restrictions on this, other annotations (e.g. @XmlID) specifically allow annotation either the setter or the getter, but not both.
Note that @XmlAttribute expects an attribute, not an element. Also, since it parses an attribute, it can't be a complex type. So EGroup could be an enum, perhaps?
I expanded your example and added some asserts, and it works "on my machine", using the latest 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();
}
}
精彩评论