生成XML时如何省略GO中的空字段

dan*_*els 4 xml go

我有以下结构:

type CustomAttribute struct {
    Id     string   `xml:"attribute-id,attr,omitempty"`
    Values []string `xml:"value,omitempty"`
}

type Store struct {
    XMLName          xml.Name          `xml:"store"`
    Id               string            `xml:"store-id,attr,omitempty"`
    Name             string            `xml:"name,omitempty"`
    Address1         string            `xml:"address1,omitempty"`
    Address2         string            `xml:"address2,omitempty"`
    City             string            `xml:"city,omitempty"`
    PostalCode       string            `xml:"postal-code,omitempty"`
    StateCode        string            `xml:"state-code,omitempty"`
    CountryCode      string            `xml:"country-code,omitempty"`
    Phone            string            `xml:"phone,omitempty"`
    Lat              float64           `xml:"latitude,omitempty"`
    Lng              float64           `xml:"longitude,omitempty"`
    CustomAttributes []CustomAttribute `xml:"custom-attributes>custom-attribute,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)

然后我初始化结构如下:

    store := &Store{
        Id:          storeId,
        Name:        row[4],
        Address1:    row[5],
        Address2:    row[6],
        City:        row[7],
        PostalCode:  row[9],
        StateCode:   row[8],
        CountryCode: row[11],
        Phone:       row[10],
    }
Run Code Online (Sandbox Code Playgroud)

所以 CustomAttributes 数组总是空的,并且 len(store.CustomAttributes) 是 0 所以知道为什么生成的 XML 仍然包含空的“custom-attributes”标签?

    <custom-attributes></custom-attributes>
Run Code Online (Sandbox Code Playgroud)

Grz*_*Żur 5

一种解决方案是使该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"},
        },
    })
}
Run Code Online (Sandbox Code Playgroud)

Playground