Jaxb 2将不同的元素映射到同一属性 [英] Jaxb 2 mapping different element to the same property
问题描述
我想知道这是否可以在jaxb2中使用。我有一个xml可以是< element>或< element2>它永远不会在某个时候出现。它们都是String类型,我希望它映射到我的java类中的相同属性。在jaxb2中有没有办法配置?
I wonder if this is possible in jaxb2. I have a xml that can be either < element > or < element2 > it will never apear at the some time. They are both of type String and I want it to map to the same property in my java class. Is there a way in jaxb2 to configure that?
谢谢
查理
推荐答案
如果您尝试序列化回XML,会发生什么?将使用哪个元素名称?
What would happen if you tried to serialize back to XML? Which element name would be used?
假设您只需要从XML反序列化为Java,那么您可以通过注释setter方法而不是字段来执行此操作:
Assuming you only need to deserialize from XML to Java, then you can do this by annotating your setter methods instead of your fields:
public class Bean {
private String value;
@XmlElement(name="element")
public void setA(String value) {
this.value = value;
}
@XmlElement(name="element2")
public void setB(String value) {
this.value = value;
}
}
您可能还需要添加 getA()
和 getB()
方法,以便JAXB正确识别setter。
You might also have to add getA()
and getB()
methods in order for JAXB to recognise the setters properly.
这篇关于Jaxb 2将不同的元素映射到同一属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!