Don*_*eba 8 xml marshalling go
经过一些追踪和错误,我想分享我正在处理的问题.
我正在填充结构并将其转换为XML(xml.Marshal)如下所示,Foo示例按预期工作.但是Bar示例创建了一个空group1.
所以我的问题是:"如果没有设置子代,我如何防止生成Group1."
package main
import (
"fmt"
"encoding/xml"
)
type Example1 struct{
XMLName xml.Name `xml:"Example1"`
Element1 string `xml:"Group1>Element1,omitempty"`
Element2 string `xml:"Group1>Element2,omitempty"`
Element3 string `xml:"Group2>Example3,omitempty"`
}
func main() {
foo := &Example1{}
foo.Element1 = "Value1"
foo.Element2 = "Value2"
foo.Element3 = "Value3"
fooOut, _ := xml.Marshal(foo)
fmt.Println( string(fooOut) )
bar := &Example1{}
bar.Element3 = "Value3"
barOut, _ := xml.Marshal(bar)
fmt.Println( string(barOut) )
}
Run Code Online (Sandbox Code Playgroud)
Foo输出:
<Example1>
<Group1>
<Element1>Value1</Element1>
<Element2>Value2</Element2>
</Group1>
<Group2>
<Example3>Value3</Example3>
</Group2>
</Example1>
Run Code Online (Sandbox Code Playgroud)
条形输出:
<Example1>
<Group1></Group1> <------ How to remove the empty parent value ?
<Group2>
<Example3>Value3</Example3>
</Group2>
</Example1>
Run Code Online (Sandbox Code Playgroud)
加成
此外,我已尝试执行以下操作,但仍生成一个空的"Group1":
type Example2 struct{
XMLName xml.Name `xml:"Example2"`
Group1 struct{
XMLName xml.Name `xml:"Group1,omitempty"`
Element1 string `xml:"Element1,omitempty"`
Element2 string `xml:"Element2,omitempty"`
}
Element3 string `xml:"Group2>Example3,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)
完整的代码可以在这里找到:http://play.golang.org/p/SHIcBHoLCG.例子来
编辑:更改了golang示例以使用MarshalIndent提高可读性
编辑2 Ainar-G Works的例子很适合隐藏空父,但填充它会让它变得更难." panic: runtime error: invalid memory address or nil pointer dereference"
Ain*_*r-G 14
Example1不起作用,因为显然,omitempty标签只适用于元素本身而不是a>b>c封闭元素.
Example2不起作用,因为,omitempty不能将空结构识别为空.来自doc:
空值为false,0,任何nil指针或接口值,以及长度为零的任何数组,切片,映射或字符串.
没有提到结构.您可以baz通过更改Group1为指向结构的指针来使示例工作:
type Example2 struct {
XMLName xml.Name `xml:"Example1"`
Group1 *Group1
Element3 string `xml:"Group2>Example3,omitempty"`
}
type Group1 struct {
XMLName xml.Name `xml:"Group1,omitempty"`
Element1 string `xml:"Element1,omitempty"`
Element2 string `xml:"Element2,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)
然后,如果要填写Group1,则需要单独分配:
foo.Group1 = &Group1{
Element1: "Value1",
}
Run Code Online (Sandbox Code Playgroud)
示例:http://play.golang.org/p/mgpI4OsHf7
| 归档时间: |
|
| 查看次数: |
5023 次 |
| 最近记录: |