2 回答

TA貢獻1799條經驗 獲得超8個贊
一種解決方案是使CustomAttributes字段成為指針。值為 時將省略nil。在Marshal文檔中查找“零值” 。
package main
import (
"encoding/xml"
"fmt"
"log"
)
type Store struct {
XMLName xml.Name `xml:"store"`
CustomAttributes *[]CustomAttribute `xml:"custom-attributes>custom-attribute,omitempty"`
}
type CustomAttribute struct {
Id string `xml:"attribute-id,attr,omitempty"`
Values []string `xml:"value,omitempty"`
}
func print(store *Store) {
data, err := xml.Marshal(store)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
}
func main() {
print(&Store{})
print(&Store{
CustomAttributes: &[]CustomAttribute{},
})
print(&Store{
CustomAttributes: &[]CustomAttribute{
{Id: "hello"},
},
})
}

TA貢獻1752條經驗 獲得超4個贊
我認為這里發生的情況是,由于您將元素的名稱指定為嵌套的,custom-attributes>custom-attribute那種暗示custom-attributes應該存在“外部”(“中間”?,“容器”?)元素- 部分原因是沒有什么可以阻止你從使用包含相同外部元素的名稱標記任意數量的其他字段 - 例如custom-attributes>foobar.
跟蹤沒有一個這樣的字段被封送的情況,因此它們的外部元素不應該被使用對于封送處理程序來說可能太多了——我想——被明確地寫成在它工作時盡可能少地保留上下文。
因此,雖然我理解您對此感到困惑,但我認為這種行為在您瞇著眼睛看久一點之后是可以理解的。
至于如何解決它,我個人會嘗試更加明確并將您的切片包裝成一種struct類型,例如
type CustomAttributes struct {
XMLName xml.Name `xml:"custom-attributes"`
Items []CustomAttribute `xml:"custom-attributes>custom-attribute"`
}
然后會有一個自定義編組器:
func (cas CustomAttributes) MarshalXML(e *xml.Encoder,
start xml.StartElement) (err error) {
if len(cas.Items) == 0 {
return nil
}
err = e.EncodeToken(start)
if err != nil {
return
}
err = e.Encode(cas.Items)
if err != nil {
return
}
return e.EncodeToken(xml.EndElement{
Name: start.Name,
})
}
- 2 回答
- 0 關注
- 181 瀏覽
添加回答
舉報