我正在尝试使用JAXB生成类似的内容:
<person>
<firstName>Foo</firstName>
<lastName>Bar</lastName>
<identities>
<green id="greenId">
<some_elements....
</green>
<blue id="blueId"/>
</identities>
<identities>
的子元素都来自一个普通的超类。
在Java中就是这样:
@XmlRootElement(name = "person")
public class Person {
public String firstName;
public String lastName;
@XmlElementWrapper(name = "identities")
public Set<Identity> identities = new HashSet<Identity>();
}
其中Identity
是Blue
,Green
和其他一些人的超类。
public class Identity {
@XmlID
@XmlAttribute
public String id;
}
@XmlRootElement(name = "blue")
public class Blue extends Identity {
public String oneOfManyFields;
}
@XmlRootElement(name = "green")
public class Green extends Identity {}
如何正确地注释类以获得我需要的东西?目前,输出如下:
<identities>
<identities id="0815"/>
</identities>
答案 0 :(得分:1)
只需修改您的示例,即可在identities属性上使用@XmlElementRef注释。
import java.util.HashSet;
import java.util.Set;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "person")
public class Person {
public String firstName;
public String lastName;
@XmlElementWrapper(name = "identities")
@XmlElementRef
public Set<Identity> identities = new HashSet<Identity>();
}