Lý do JAXB thực hiện điều này là khớp với kế thừa trong lược đồ XML. Tuy nhiên, bạn có thể làm một cái gì đó như sau:
- Đánh dấu @XmlTransient mẹ
- Đặt propOrder trên lớp con
Chánh
import javax.xml.bind.annotation.XmlTransient;
@XmlTransient
public abstract class Parent {
private String parentProp;
public String getParentProp() {
return parentProp;
}
public void setParentProp(String parentProp) {
this.parentProp = parentProp;
}
}
Child
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement
@XmlType(propOrder={"childProp", "parentProp"})
public class Child extends Parent {
private String childProp;
public String getChildProp() {
return childProp;
}
public void setChildProp(String childProp) {
this.childProp = childProp;
}
}
Demo
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Child.class);
Child child = new Child();
child.setParentProp("parent-value");
child.setChildProp("child-value");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(child, System.out);
}
}
Output
<child>
<childProp>child-value</childProp>
<parentProp>parent-value</parentProp>
</child>
Nguồn
2011-03-22 17:05:52
câu trả lời mát mẻ, 1. làm điều này làm việc với xác nhận lược đồ (khi unmarshalling)? 2. nó sẽ làm việc với @XmlTransient nhưng không có mệnh đề – ekeren
@ekeren - 1. Phụ thuộc vào lược đồ XML trông như thế nào, nếu có sự kế thừa giữa các kiểu phức tạp thì các thuộc tính kiểu cha sẽ xuất hiện trước các thuộc tính kiểu con. 2. Có, nhưng không có propOrder thứ tự phụ thuộc vào JAXB impl. –
@BlaiseDoughan có cách nào khác để có các thuộc tính con đầu tiên mà không có thuộc tính cha mẹ hartcoding không? có chú thích như chú thích con này, nó vi phạm một chút mô hình OOP ... Tôi đang sử dụng EclipseLink MOXy – basZero