开发者

Order xml superclass elements in Java serialization

开发者 https://www.devze.com 2023-02-18 20:08 出处:网络
I have two classes ParentClass and ChildClass in JAVA using JAXB. ChildClass extends ParentClass. When I serialize an object of ChildClass,开发者_运维技巧 in the resulting XML, ParentClass properties

I have two classes ParentClass and ChildClass in JAVA using JAXB. ChildClass extends ParentClass. When I serialize an object of ChildClass,开发者_运维技巧 in the resulting XML, ParentClass properties appear first, I would like to have ChildClass properties first and then ParentClass properties.

Is this possible?

Thank you


The reason JAXB does this is to match inheritance in XML schema. However, you could do something like the following:

  • Mark the parent @XmlTransient
  • Set the propOrder on the child class

Parent

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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号