在Go语言中解组XML时,可以通过省略空数组元素来实现。

huangapple go评论79阅读模式
英文:

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 (
    &quot;fmt&quot;
    &quot;encoding/xml&quot;
    &quot;bytes&quot;
)

type foo struct {
    Bars []string `xml:&quot;bar,omitempty&quot;`
}

func main() {
    xmlStr := `
        &lt;foo&gt;
	        &lt;bar&gt;1&lt;/bar&gt;
	        &lt;bar&gt;&lt;/bar&gt;
	        &lt;bar&gt;2&lt;/bar&gt;
        &lt;/foo&gt;`

    var f foo
    xml.NewDecoder(bytes.NewBufferString(xmlStr)).Decode(&amp;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 != &quot;&quot; {
            res = append(res, s)
        }
    }
    return res
}

huangapple
  • 本文由 发表于 2017年3月17日 20:11:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/42857246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定