2011-03-22 15 views
6

JAXBを使用してJAVAのParentClassとChildClassをクラス化する必要があります。 ChildClassはParentClassを継承します。 ChildClassのオブジェクトをシリアル化すると、結果のXMLでは、ParentClassプロパティが最初に表示されます。まず、ChildClassプロパティとParentClassプロパティが必要です。Java直列化でxmlスーパークラス要素を注文する

これは可能ですか?

答えて

9

にJAXBが、これはXMLスキーマで継承を一致させるためにあるん理由をいただき、ありがとうございます。しかし、あなたのような何かを行うことができ、次の

  • マーク子クラス

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

} 

子供にpropOrderを設定し、親@XmlTransient

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

    クールな答えは、1。これはスキーマ検証(アンマーシャリング時)で機能しますか? @XmlTransientでは動作するが、プロポーザなしで動作するかどうか – ekeren

    +1

    @ekeren - 1. XMLスキーマがどのように見えるかに依存して、複合型間に継承がある場合、子型プロパティの前に親型プロパティが発生することが予想されます。 2.はい、propOrderを指定しないと、順序はJAXB implに依存します。 –

    +0

    @BlaiseDoughanには、親プロパティをhartcodingせずに子プロパティを最初に持つ別の方法がありますか?これらの子注釈のような注釈を持つと、OOPのパラダイムに少し違反します...私はEclipseLink MOXyを使用しています – basZero

    関連する問題