Заказать элементы суперкласса xml в сериализации Java - PullRequest
6 голосов
/ 22 марта 2011

У меня есть классы ParentClass и ChildClass в JAVA, использующие JAXB. ChildClass расширяет ParentClass. Когда я сериализую объект ChildClass, в результирующем XML сначала появляются свойства ParentClass, я хотел бы сначала иметь свойства ChildClass, а затем свойства ParentClass.

Возможно ли это?

Спасибо

1 Ответ

9 голосов
/ 22 марта 2011

Причина, по которой JAXB делает это, заключается в сопоставлении наследования в схеме XML.Однако вы можете сделать что-то вроде следующего:

  • Отметить родительский @ XmlTransient
  • Установить propOrder для дочернего класса

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;
    }

}

Демо

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