jaxb XmlAccessType:属性示例 [英] jaxb XmlAccessType: PROPERTY example
问题描述
我正在尝试使用jaxb,并且想使用'XmlAccessType.PROPERTY'让jaxb使用getters/setters而不是直接使用变量,但是根据我尝试的内容或变量而不同的错误根本没有我想要的设置.
I'm trying to use jaxb and 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?
例如,下面使groupDefintion不在解析xml文档时设置:
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;
}
}
推荐答案
答案是您的示例本身并没有错,但是有一些可能的陷阱.您已将注释放在设置器上,而不是在获取器上.虽然JavaDoc for @XmlAttribute对此没有任何限制,但其他批注(例如@XmlID)专门允许批注者或吸气剂,但不能同时批注.
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.
请注意,@ XmlAttribute需要一个属性,而不是一个元素.另外,由于它解析属性,因此它不能是复杂的类型.那么EGroup可能是一个枚举?
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?
我扩展了您的示例并添加了一些断言,它使用最新的Java 6在我的机器上"工作.
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();
}
}
这篇关于jaxb XmlAccessType:属性示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!