您的位置:首页 > 编程语言 > Go语言

golang xml解析不确定是否存在的元素

2017-08-29 15:41 726 查看
golang中负责解析函数

func Unmarshal(data []byte, v interface{}) error

只能对struct, slice和string进行解析
golang中负责生成xml函数

func Marshal(v interface{}) ([]byte, error)marshal可以处理指针指向的值, 若指针为nil, 则不会写入到xml中.
我们可以在定义解析的struct结构时, 将元素的类型定义为指针类型, 若解析时不存在该元素, 则在marshal时不会生成空的元素.

type ObjectInfo struct {
// attr
ObjectType string `xml:"ObjectType,attr"`
Id string `xml:"Id,attr"`
Name string `xml:"Name,attr"`
CreationDate string //`xml:"CreationDate"` // struct tag is not necessary
// tag
Tag []TagInfo `xml:"TagCollection>Tag"`
// ColorValues
RefSpecData *ReflectanceSpectrumInfo `xml:"ColorValues>ReflectanceSpectrum"`
ColorLabData *ColorCIELabInfo `xml:"ColorValues>ColorCIELab"`
ColorDensityData *ColorDensityInfo `xml:"ColorValues>ColorDensity"`
//ColorValues PrintDataInterface `xml:",innerxml"`

// DeviceColorValues
ColorCMYKPlusNData *ColorCMYKPlusNInfo `xml:"DeviceColorValues>ColorCMYKPlusN"`
ColorCMYKData *ColorCMYKInfo `xml:"DeviceColorValues>ColorCMYK"`
//DeviceColorValues PrintDataInterface `xml:",innerxml"`
}上面结构是在解析CxF定义的结构, 扫描后生成的数据类型是不确定的, 但又是固定的几组结构, 指针类型能很好的解决这个问题.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐