2012-06-05 25 views
2

JAXB通行證通過考慮以下類映射

@XmlRootElement(name = "parent") 
class Parent { 
    private Child child; 

    // What annotation goes here 
    public Child getChild() { 
    return child; 
    } 

    public void setChild(Child child) { 
    this.child = child; 
    } 
} 

class Child { 
    private Integer age; 

    @XmlElement(name = "age") 
    public Integer getAge() { 
    return age; 
    } 

    public void setAge(Integer Age) { 
    this.age = age; 
    } 

} 

什麼註解,我需要增加(其中評論是),以獲得以下XML:

<parent> 
    <age>55</age> 
</parent> 

我剛纔提出的具體例如關閉我的頭頂,讓標籤出現在可能沒有意義的地方。但我真正想知道的是如何對Child類進行傳遞。本質上它很容易做到的映射以下(我不希望):

<parent> 
    <child> 
    <age>55</age> 
    </child> 
</parent> 
+1

我懷疑你能在確保孩子落一個子元素。您可以使用@XmlTransient註釋去除元素,但這也意味着要省略它們的內容。要從第二個列表中獲取XML,您需要在Parent類中創建一個age屬性。 – toniedzwiedz

+1

[JAXB的可能的重複 - 可以將類封裝在編組爲XML時展平?](http://stackoverflow.com/questions/8361634/jaxb-can-class-containment-be-flattened-when-marshalling-to-xml ) –

回答

0
import javax.xml.bind.*; 
import javax.xml.bind.annotation.*; 

@XmlRootElement 
class Parent { 

    public static void main(String[] args) throws JAXBException { 

     final Child child = new Child(); 
     child.age = 55; 

     final Parent parent = new Parent(); 
     parent.child = child; 

     final JAXBContext context = JAXBContext.newInstance(Parent.class); 
     final Marshaller marshaller = context.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, 
           Boolean.TRUE); 
     marshaller.marshal(parent, System.out); 
     System.out.flush(); 
    } 

    @XmlElement 
    public Integer getAge() { 
     return child == null ? null : child.age; 
    } 

    @XmlTransient 
    private Child child; 
} 

class Child { 

    @XmlElement 
    protected Integer age; 
} 

打印

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<parent> 
    <age>55</age> 
</parent>