Optional "omitempty" when marshalling XML?

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

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:

&lt;items&gt;
    &lt;item autocomplete=&quot;My Thing&quot;&gt;
        &lt;title&gt;My Thing&lt;/title&gt;
    &lt;/item&gt;
    &lt;item&gt;
        &lt;title&gt;My Other Thing&lt;/title&gt;
    &lt;/item&gt;
    &lt;item autocomplete=&quot;&quot;&gt;
        &lt;title&gt;My Third Thing&lt;/title&gt;
    &lt;/item&gt;
&lt;/items&gt;

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).

Play

type Address struct {
	City *string
}

city1 := &quot;NYC&quot;
city2 := &quot;&quot;
address1 := Address{&amp;city1}
address2 := Address{&amp;city2}
address3 := Address{nil}

enc := xml.NewEncoder(os.Stdout)

enc.Encode(address1) // &lt;Address&gt;&lt;City&gt;NYC&lt;/City&gt;&lt;/Address&gt;
enc.Encode(address2) // &lt;Address&gt;&lt;City&gt;&lt;/City&gt;&lt;/Address&gt;
enc.Encode(address3) // &lt;Address&gt;&lt;/Address&gt;

huangapple
  • 本文由 发表于 2016年3月28日 19:15:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/36261195.html
匿名

发表评论

匿名网友

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

确定