Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“可选”;省略“空”;什么时候编组XML?_Xml_Go_Marshalling - Fatal编程技术网

“可选”;省略“空”;什么时候编组XML?

“可选”;省略“空”;什么时候编组XML?,xml,go,marshalling,Xml,Go,Marshalling,我正在尝试为Alfred 2应用程序生成XML。看起来有点像这样: <items> <item autocomplete="My Thing"> <title>My Thing</title> </item> <item> <title>My Other Thing</title> </item> <item a

我正在尝试为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的行为与设置为空字符串时不同

因此,我希望能够提供两种可能性:默认情况下省略属性(
ommitempty
),但提供强制将其设置为空字符串的可能性(而不是
ommitempty


我该怎么做呢?

您可以在要封送的结构中使用指针。如果指针为
nil
,则该字段将被忽略。如果它指向一个字符串,它将被渲染(即使该字符串为空)

类型地址结构{
城市*字符串
}
城市1:=“纽约市”
城市2:=“”
地址1:=地址{&city1}
地址2:=地址{&city2}
地址3:=地址{nil}
enc:=xml.NewEncoder(os.Stdout)
enc.Encode(地址1)//纽约
附件编码(地址2)//
附件编码(地址3)//

谢谢你的回答。我希望避免这样做,因为几乎每个值都是一个字符串,所以API将是一堆令人厌恶的字符串指针。我想我必须“手工”生成XML。
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>