首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生成XML时如何省略GO中的空字段

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

Stack Overflow用户
提问于 2016-05-12 11:03:28
回答 1查看 3.9K关注 0票数 4

我有以下结构:

代码语言:javascript
复制
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"`
}

然后,我将结构初始化如下:

代码语言:javascript
复制
    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仍然包含空的“自定义属性”标记吗?

代码语言:javascript
复制
    <custom-attributes></custom-attributes>
EN

回答 1

Stack Overflow用户

发布于 2016-05-12 19:12:33

我认为这里发生的事情是,既然您将元素的名称指定为嵌套,那么custom-attributes>custom-attribute就意味着“外层”(“中间”、“容器”)?元素,custom-attributes应该存在--部分原因是没有什么可以阻止您用名称标记任何其他字段,包括相同的外部元素--比如custom-attributes>foobar

跟踪这种情况,没有任何这样的字段被封送,因此它们的外部元素不应该被使用,对于封送处理程序来说可能太多了,我认为它是显式编写的,以便在它工作时保持尽可能少的上下文。

因此,虽然我理解你感到困惑,但我认为,这种行为是可以理解的,只要你斜视它再长一点。

至于如何解决这个问题,我会亲自尝试更明确地将您的切片包装成一个struct类型,例如

代码语言:javascript
复制
type CustomAttributes struct {
    XMLName xml.Name `xml:"custom-attributes"`
    Items []CustomAttribute `xml:"custom-attributes>custom-attribute"`
}

然后就会有一个自定义的封送员:

代码语言:javascript
复制
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,
    })
}

操场链接

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37185026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档