2012-12-11 44 views
8

對於以下示例XSD片段:JAXB xjc:如何爲字符串生成代碼,如果值爲空則返回空值?

< xs:attribute name="SEGMENT" default="" use="optional" type="xs:string"/ > 

時XJC生成包含SEGMENT豆屬性類,下面的吸氣劑是自動生成的:

public String getSEGMENT() { 
    if (segment == null) { 
     return ""; 
    } else { 
     return segment; 
    } 
} 

我的問題是你如何得到它對xs:element對象做同樣的事情嗎?換句話說,鑑於以下XSD片段:

< xs:element name="NAME" default="" type="xs:string"/ > 

我想知道如果我能得到XJC生成以下:

public String getNAME() { 
    if (name == null) { 
     return ""; 
    } else { 
     return name; 
    } 
} 

如何才能做到這一點?因爲它爲默認值的屬性

回答

2

JAXB不生成默認值的元件相同的代碼,因爲XML schema differentiates between element and attribute defaults

Default values of both attributes and elements are declared using the default attribute, although this attribute has a slightly different consequence in each case. When an attribute is declared with a default value, the value of the attribute is whatever value appears as the attribute's value in an instance document; if the attribute does not appear in the instance document, the schema processor provides the attribute with a value equal to that of the default attribute. Note that default values for attributes only make sense if the attributes themselves are optional, and so it is an error to specify both a default value and anything other than a value of optional for use.

The schema processor treats defaulted elements slightly differently. When an element is declared with a default value, the value of the element is whatever value appears as the element's content in the instance document; if the element appears without any content, the schema processor provides the element with a value equal to that of the default attribute. However, if the element does not appear in the instance document, the schema processor does not provide the element at all. In summary, the differences between element and attribute defaults can be stated as: Default attribute values apply when attributes are missing, and default element values apply when elements are empty.

您可以在默認值總是計數丟失屬性(從這裏是特殊的獲取者),但有一個缺少元素值的捕獲。

儘管如此,當您解組一個實例時,解組器會知道如何處理默認值。看到這裏的細節:

XJC不會添加默認值,吸氣代碼或初始化領域,所以如果你需要「空安全檢查」你可以自行添加手動由XJC生成的代碼之後或嘗試用一些插件來自動執行:

+0

一個字段初始肯定是合適的。現在的問題是如何讓xjc爲每個類的每個字符串添加空字符串初始值設定項?也許在一個單獨的綁定文件? –

+0

@java luva:我在回答中添加了更多細節,並且發現了一些看起來很有趣的插件。看看它是否有幫助。 – Bogdan

+0

感謝您的額外信息。我有一個問題,但。您發送的鏈接涉及設置maven或ant任務。我不使用maven。而設置螞蟻任務時的問題是我得到一個鏈接錯誤,指出不同的類將被加載相同的名稱。我相信問題是java 1.6內置了xjc,並且通過將jaxb-xjc-2.1.9.jar添加到我的xjc taskdef類路徑中,它們發生衝突。我的問題是如何讓ant腳本忽略1.6(我的JAVA_HOME設置爲)並使用我的taskdef類路徑,或者在taskdef中引用1.6 xjc jar? –

相關問題