golang 解析XMl encoding/xml.Marshal
1 | package main |
其中Height float32 `xml:"height,omitempty"`
这里的omitempty 用于表示如果Height 为空则不输出在XML 中,文档中解释为:
1
2
3
4 - a field with a tag including the "omitempty" option is omitted
if the field value is empty. The empty values are false, 0, any
nil pointer or interface value, and any array, slice, map, or
string of length zero.
使用时发现对于struct,例如:
1 | type Email struct { |
如果Email 没有赋予初值,运行时成员Test仍然会被放到XML里,而不是丢弃:
1 | package main |
输出结果:
1
2
3
4
5
6
7
8
9 <Person>
<Name>myname</Name>
<Test where="">
<Addr></Addr>
</Test>
</Person>
XMLName: xml.Name{Space:"", Local:""}
Name: "myname"
Test: {"" ""}
经查询,文档里确实没有明确指明如果元素是个结构体,即便是空的也不会被忽略,但文档里有说如果是个指针,空的就可以忽略了:
1 | type Result struct { |
1
2
3
4
5
6 <Person>
<Name>myname</Name>
</Person>
XMLName: xml.Name{Space:"", Local:""}
Name: "myname"
Test: %!q(*main.Email=<nil>)