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

标签 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"`
}

然后我按如下方式初始化结构:

    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],
    }

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

    <custom-attributes></custom-attributes>

最佳答案

一种解决方案是使 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"},
        },
    })
}

Playground

关于xml - 如何在生成 XML 时省略 GO 中的空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37185026/

相关文章:

go - 如何获取目录总大小?

io - 为什么 io.WriterString 会出现运行时错误?

Golang (v1.8) - 错误 : type *mux. Route has no field or method Method

xml - 定义 xml 的相等性

c - libxml2 所有 xml 转 char

php - 如何使用 PHP 从 XML 文件检索内容 - YouTube API

go - 如何在 Go 中将函数存储在 slice 中

xml - XSLT : Using choose to transform tag value depending on true/false

java - API 19 : android. view.InflateException:二进制 XML 文件行 #0:膨胀类 SeekBar 时出错

在文件更改时自动重新编译和重新加载服务器