在Java序列化中排序xml超类元素
发布时间:2020-12-14 05:46:43 所属栏目:Java 来源:网络整理
导读:我必须使用JAXB在JAVA中对ParentClass和ChildClass进行分类. ChildClass扩展了ParentClass. 当我序列化ChildClass的一个对象时,在生成的 XML中,ParentClass属性首先出现,我想首先使用ChildClass属性,然后是ParentClass属性. 这可能吗? 谢谢 解决方法 JAXB执
|
我必须使用JAXB在JAVA中对ParentClass和ChildClass进行分类.
ChildClass扩展了ParentClass. 当我序列化ChildClass的一个对象时,在生成的 XML中,ParentClass属性首先出现,我想首先使用ChildClass属性,然后是ParentClass属性. 这可能吗? 谢谢 解决方法
JAXB执行此操作的原因是为了匹配XML模式中的继承.但是,您可以执行以下操作:
>标记父@XmlTransient 亲 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;
}
}
儿童 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;
}
}
演示 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);
}
}
产量 <child>
<childProp>child-value</childProp>
<parentProp>parent-value</parentProp>
</child>
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
