How to marshal xml in Go but ignore empty fields

huangapple go评论100阅读模式
英文:

How to marshal xml in Go but ignore empty fields

问题

如果我有一个结构体,我想要能够使用encoding/xml将其转换为xml格式并进行反转换,那么我该如何打印空属性呢?

package main

import (
	"encoding/xml"
	"fmt"
)

type MyThing struct {
	XMLName xml.Name `xml:"body"`
	Name    string   `xml:"name,attr"`
	Street  string   `xml:"street,attr,omitempty"`
}

func main() {
	var thing *MyThing = &MyThing{Name: "Canister"}
	result, _ := xml.Marshal(thing)
	fmt.Println(string(result))
}

例如,参考http://play.golang.org/p/K9zFsuL1Cw

在上面的示例中,我不想输出空的street属性;我该如何做到这一点?

英文:

If I have a struct which I want to be able to Marhsal/Unmarshal things in and out of xml with (using encoding/xml) - how can I not print attributes which are empty?

package main

import (
	"encoding/xml"
	"fmt"
)

type MyThing struct {
	XMLName xml.Name `xml:"body"`
	Name    string   `xml:"name,attr"`
	Street  string   `xml:"street,attr"`
}

func main() {
	var thing *MyThing = &MyThing{Name: "Canister"}
	result, _ := xml.Marshal(thing)
	fmt.Println(string(result))
}

For example see http://play.golang.org/p/K9zFsuL1Cw

In the above playground I'd not want to write out my empty street attribute; how could I do that?

答案1

得分: 12

street字段上使用omitempty标记。

根据Go XML包的说明:

> - 如果字段的标记包含"omitempty"选项,则在字段值为空时将其省略。空值包括false、0、任何nil指针或接口值,以及长度为零的任何数组、切片、映射或字符串。

以你的示例为例:

package main

import (
	"encoding/xml"
	"fmt"
)

type MyThing struct {
	XMLName xml.Name `xml:"body"`
	Name    string   `xml:"name,attr"`
	Street  string   `xml:"street,attr,omitempty"`
}

func main() {
	var thing *MyThing = &MyThing{Name: "Canister"}
	result, _ := xml.Marshal(thing)
	fmt.Println(string(result))
}

<kbd>Playground</kbd>

英文:

Use omitempty flag on street field.

From Go XML package:

> - a field with a tag including the "omitempty" option is omitted
if the field value is empty. The empty values are false, 0, any
nil pointer or interface value, and any array, slice, map, or
string of length zero.

In case of your example:

package main

import (
	&quot;encoding/xml&quot;
	&quot;fmt&quot;
)

type MyThing struct {
	XMLName xml.Name `xml:&quot;body&quot;`
	Name    string   `xml:&quot;name,attr&quot;`
	Street  string   `xml:&quot;street,attr,omitempty&quot;`
}

func main() {
	var thing *MyThing = &amp;MyThing{Name: &quot;Canister&quot;}
	result, _ := xml.Marshal(thing)
	fmt.Println(string(result))
}

<kbd>Playground</kbd>

huangapple
  • 本文由 发表于 2015年9月7日 18:51:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/32436885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定