JAXB通行证通过考虑以下类映射
问题描述:
@XmlRootElement(name = "parent")
class Parent {
private Child child;
// What annotation goes here
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
class Child {
private Integer age;
@XmlElement(name = "age")
public Integer getAge() {
return age;
}
public void setAge(Integer Age) {
this.age = age;
}
}
什么注解,我需要增加(其中评论是),以获得以下XML:
<parent>
<age>55</age>
</parent>
我刚才提出的具体例如关闭我的头顶,让标签出现在可能没有意义的地方。但我真正想知道的是如何对Child类进行传递。本质上它很容易做到的映射以下(我不希望):
<parent>
<child>
<age>55</age>
</child>
</parent>
答
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
@XmlRootElement
class Parent {
public static void main(String[] args) throws JAXBException {
final Child child = new Child();
child.age = 55;
final Parent parent = new Parent();
parent.child = child;
final JAXBContext context = JAXBContext.newInstance(Parent.class);
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
marshaller.marshal(parent, System.out);
System.out.flush();
}
@XmlElement
public Integer getAge() {
return child == null ? null : child.age;
}
@XmlTransient
private Child child;
}
class Child {
@XmlElement
protected Integer age;
}
打印
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<parent>
<age>55</age>
</parent>
我怀疑你能在确保孩子落一个子元素。您可以使用@XmlTransient注释去除元素,但这也意味着要省略它们的内容。要从第二个列表中获取XML,您需要在Parent类中创建一个age属性。 – toniedzwiedz
[JAXB的可能的重复 - 可以将类封装在编组为XML时展平?](http://stackoverflow.com/questions/8361634/jaxb-can-class-containment-be-flattened-when-marshalling-to-xml ) –