2010-01-21 44 views
3

不確定標題是否有意義。 我有我想用JAXB,看起來像這樣編組的對象:編組具有對象字段的對象

@XmlRootElement(name = "subscriptionRequest") 
    public class RegistrationRequest { 

    private Long id; 
    private RegistrationSource registrationSource; 
    } 

的RegistrationSource對象:

public class RegistrationSource { 

    private Integer id; 
    private String code; 
} 

我想創建具有以下佈局的XML:

<subscriptionRequest registrationSource="0002"> 
    ... 
</subscriptionRequest> 

其中registrationSource屬性值是RegistrationSource對象的代碼字段值。

我需要使用哪些xml註釋?

回答

6

@XmlAttribute on registrationSource,@XmlValue on code。請注意,在這種情況下,你也應該對RegistrationSource等領域有@XmlTransient,如id

編輯:這工作:

@XmlRootElement(name = "subscriptionRequest") 
public class RegistrationRequest { 

    private Long id; 
    private RegistrationSource registrationSource; 

    public Long getId() { return id; } 
    public void setId(Long id) { this.id = id; } 

    @XmlAttribute 
    public RegistrationSource getRegistrationSource() { return registrationSource; } 
    public void setRegistrationSource(RegistrationSource registrationSource) 
    { 
     this.registrationSource = registrationSource; 
    } 
} 

-

public class RegistrationSource { 

    private Integer id; 
    private String code; 

    @XmlTransient 
    public Integer getId() { return id; } 
    public void setId(Integer id) { this.id = id; } 

    @XmlValue 
    public String getCode() { return code; } 
    public void setCode(String code) { this.code = code; } 
} 
+0

我得到以下異常: 異常線程「main」 com.sun.xml.bind.v2.runtime.IllegalAnnotationsException:IllegalAnnotationExceptions 1個計數 @XmlValue不允許在派生另一個類的類。 – Imhotep 2010-01-21 16:12:31

+0

@Imhotep:我添加了工作代碼。 – axtavt 2010-01-21 16:46:29

+0

在你寫下這段代碼之前,我把註釋放在字段聲明中。之後,我看到了你的代碼和應用的變化,我得到這些:在線程「主要」 com.sun.xml.bind.v2.runtime.IllegalAnnotationsException 例外:IllegalAnnotationExceptions的5個計數 @XmlValue不允許在類導出另一類。 。 如果一個類具有@XmlElement屬性,則它不能具有@XmlValue屬性。 。 @ XmlAttribute/@ XmlValue需要引用映射到XML中的文本的Java類型。 。 類有兩個名稱相同的屬性「registrationSource」 。 類有兩個同名「代碼」的屬性 – Imhotep 2010-01-21 17:19:43

0

跛腳的方法是添加如

@XmlAttribute(name = "registrationSource") 
private String getCode() { 
    return registrationSource.code; 
} 

RegistrationSource - 但必須有一個更優雅的方式......

+0

這一個工程,但正如你所說,它有點跛腳。我會等待對其他建議的迴應,如果沒有其他可能的解決方案,我會將其標記爲已接受的解決方案。謝謝 ps:這就像你之前提到的第二個解決方案,但似乎他刪除了他的帖子。 – Imhotep 2010-01-21 16:25:22

+0

我必須注意到,在這種情況下,我還必須將@XmlTransient註釋放在registrationSource對象上,以便它不會顯示爲元素。 – Imhotep 2010-01-21 16:33:12

1

如果你想生成這個類自動使用一些工具,那就試試這個 - 使用工具,如Trang從XML生成XSD和然後使用jaxb從xsd生成java文件。生活就會簡單得多:)

相關問題