我尝试解码一个我想省略空元素的 xml 数组。
我希望下面的代码打印 2,因为第二个 bar 元素是空的。而是打印 3。
package main
import (
"fmt"
"encoding/xml"
"bytes"
)
type foo struct {
Bars []string `xml:"bar,omitempty"`
}
func main() {
xmlStr := `
<foo>
<bar>1</bar>
<bar></bar>
<bar>2</bar>
</foo>`
var f foo
xml.NewDecoder(bytes.NewBufferString(xmlStr)).Decode(&f)
fmt.Println(len(f.Bars))
}
Go Playground 链接:https://play.golang.org/p/co8QxkyKTv
最佳答案
除非你想进入 xml.Unmarshaler
黑暗魔法,否则我建议你去做
func compact(ss []string) []string {
res := make([]string, 0, len(ss))
for _, s := range ss {
if s != "" {
res = append(res, s)
}
}
return res
}
关于arrays - 在 go 中解码 xml 时省略空数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42857246/