英文:
Optional "omitempty" when marshalling XML?
问题
我正在尝试为Alfred 2应用程序生成XML。看起来有点像这样:
<items>
<item autocomplete="My Thing">
<title>My Thing</title>
</item>
<item>
<title>My Other Thing</title>
</item>
<item autocomplete="">
<title>My Third Thing</title>
</item>
</items>
我面临的具体挑战是,如果item
上的autocomplete
属性缺失,Alfred的行为与将其设置为空字符串时不同。
因此,我希望能够提供两种可能性:默认情况下省略属性(omitempty
),但也能够强制将其设置为空字符串(不是 omitempty
)。
我该如何实现这一点?
英文:
I'm trying to generate XML for the Alfred 2 application. Looks kinda like this:
<items>
<item autocomplete="My Thing">
<title>My Thing</title>
</item>
<item>
<title>My Other Thing</title>
</item>
<item autocomplete="">
<title>My Third Thing</title>
</item>
</items>
The specific challenge I'm facing is that Alfred behaves differently if the autocomplete
attribute on item
is missing than if it is set to an empty string.
As a result, I'd like to be able to offer both possibilities: omit the attribute by default (omitempty
), but offer the possibility to force it to be set to an empty string (not omitempty
).
How could I go about doing this?
答案1
得分: 1
你可以在要编组的结构体中使用指针。如果指针为nil
,则该字段将被省略。如果指针指向一个字符串,即使该字符串为空,它也会被渲染。
示例代码如下:
type Address struct {
City *string
}
city1 := "NYC"
city2 := ""
address1 := Address{&city1}
address2 := Address{&city2}
address3 := Address{nil}
enc := xml.NewEncoder(os.Stdout)
enc.Encode(address1) // <Address><City>NYC</City></Address>
enc.Encode(address2) // <Address><City></City></Address>
enc.Encode(address3) // <Address></Address>
你可以点击这里查看示例代码的运行结果。
英文:
You can use pointers in the struct you are going to marshal. In case the pointer is nil
the field will be omitted. In case it is pointing to a string it will be rendered (even if the string is empty).
type Address struct {
City *string
}
city1 := "NYC"
city2 := ""
address1 := Address{&city1}
address2 := Address{&city2}
address3 := Address{nil}
enc := xml.NewEncoder(os.Stdout)
enc.Encode(address1) // <Address><City>NYC</City></Address>
enc.Encode(address2) // <Address><City></City></Address>
enc.Encode(address3) // <Address></Address>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论