2016-03-28 20 views
1

我正在嘗試爲Alfred 2應用程序生成XML。看起來有點像這樣:編組XML時可選「omitempty」?

<items> 
    <item autocomplete="My Thing"> 
     <title>My Thing</title> 
    </item> 
    <item> 
     <title>My Other Thing</title> 
    </item> 
    <item autocomplete=""> 
     <title>My Third Thing</title> 
    </item> 
</items> 

我面臨的具體挑戰是阿爾弗雷德的行爲不同,如果在itemautocomplete屬性缺少比如果它被設置爲空字符串。

結果,我希望能夠提供兩種可能性:在默認情況下(omitempty)省略了屬性,但提供的可能性,以迫使它被設置爲空字符串(omitempty)。

我該怎麼去做這件事?

回答

1

你可以在你要編組的結構中使用指針。如果指針是nil,則該字段將被忽略。如果它指向一個字符串,它將被渲染(即使字符串是空的)。

Play

type Address struct { 
    City *string 
} 

city1 := "NYC" 
city2 := "" 
address1 := Address{&city1} 
address2 := Address{&city2} 
address3 := Address{nil} 

enc := xml.NewEncoder(os.Stdout) 

enc.Encode(address1) // <Address><City>NYC</City></Address> 
enc.Encode(address2) // <Address><City></City></Address> 
enc.Encode(address3) // <Address></Address> 
+0

感謝您的回答。我希望避免這樣做,因爲幾乎每個值都是一個字符串,所以這個API將會是對字符串指針的排斥。我想我將不得不手動生成XML。 – wbg