英文:
Omitting empty array elements when unmarshalling xml in go
问题
我尝试解析一个 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
英文:
I try to unmarshal an xml array where I want to omit empty elements.
I would expect the following code to print 2, as the second bar element is empty. Instead 3 is printed.
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 link: https://play.golang.org/p/co8QxkyKTv
答案1
得分: 0
除非你想深入了解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
}
英文:
Unless you want to get into xml.Unmarshaler
dark magic, I'd suggest just do
func compact(ss []string) []string {
res := make([]string, 0, len(ss))
for _, s := range ss {
if s != "" {
res = append(res, s)
}
}
return res
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论