經(jīng)過一些跟蹤和錯誤后,我想分享我正在處理的問題。我正在填充一個結(jié)構(gòu)并將其轉(zhuǎn)換為 XML ( xml.Marshal ) 正如您在下面看到的 Foo 示例按預(yù)期工作。然而,Bar 示例創(chuàng)建了一個空的 group1。所以我的問題是:“如果沒有設(shè)置孩子,我如何防止生成 Group1。”package mainimport ( "fmt" "encoding/xml")type Example1 struct{ XMLName xml.Name `xml:"Example1"` Element1 string `xml:"Group1>Element1,omitempty"` Element2 string `xml:"Group1>Element2,omitempty"` Element3 string `xml:"Group2>Example3,omitempty"`}func main() { foo := &Example1{} foo.Element1 = "Value1" foo.Element2 = "Value2" foo.Element3 = "Value3" fooOut, _ := xml.Marshal(foo) fmt.Println( string(fooOut) ) bar := &Example1{} bar.Element3 = "Value3" barOut, _ := xml.Marshal(bar) fmt.Println( string(barOut) )}富輸出:<Example1> <Group1> <Element1>Value1</Element1> <Element2>Value2</Element2> </Group1> <Group2> <Example3>Value3</Example3> </Group2></Example1>條形輸出:<Example1> <Group1></Group1> <------ How to remove the empty parent value ? <Group2> <Example3>Value3</Example3> </Group2></Example1>添加此外,我嘗試執(zhí)行以下操作,但仍會生成一個空的“Group1”:type Example2 struct{ XMLName xml.Name `xml:"Example2"` Group1 struct{ XMLName xml.Name `xml:"Group1,omitempty"` Element1 string `xml:"Element1,omitempty"` Element2 string `xml:"Element2,omitempty"` } Element3 string `xml:"Group2>Example3,omitempty"`}完整代碼可以在這里找到:http : //play.golang.org/p/SHIcBHoLCG。例如編輯:更改 golang 示例以使用 MarshalIndent 以提高可讀性編輯 2 Ainar-G 中的示例適用于隱藏空父級,但填充它使它變得更加困難。“ panic: runtime error: invalid memory address or nil pointer dereference”
- 1 回答
- 0 關(guān)注
- 203 瀏覽
添加回答
舉報
0/150
提交
取消