为什么简单的XML解析器不能填充结构体?

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

Why simple XML parser doesn't fill struct

问题

尝试实现一个简单的XML解析,下面的代码不按预期工作。
它只返回一个{[]}空的Results,而它应该填充它。

为什么呢?...

package main
import "fmt"
import "encoding/xml"
import "bytes"

type Name struct {
    Name string `xml:"NAME"`
}
type Results struct {
    Names []Name `xml:"RESULTS"`
}

func main() {
    data := []byte(`
    <?xml version="1.0" encoding="UTF-8"?>
    <RESULTS>
        <NAME>Apple</NAME>
        <NAME>Banana</NAME>
    </RESULTS>
    `)
    var r Results
    decoder := xml.NewDecoder(bytes.NewBuffer(data))
    unError := decoder.Decode(&r)
    if unError != nil {
        fmt.Println("XML Unmarshaling error:", unError)
    } else {
        fmt.Printf("%v", r)
    }
}

在Playground和本地go1.17.2中尝试过

<details>
<summary>英文:</summary>

Trying to implement a simple XML parsing, the code below doesn&#39;t work as expected.  
It just returns a `{[]}` empty `Results`, while it should fill it.

Why ?...

    package main
    import &quot;fmt&quot;
    import &quot;encoding/xml&quot;
    import &quot;bytes&quot;
    
    type Name struct {
	    Name	string	`xml:&quot;NAME&quot;`
    }
    type Results struct {
	    Names	[]Name `xml:&quot;RESULTS&quot;`
    }

    func main() {
	    data := []byte(`
    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    &lt;RESULTS&gt;
     &lt;NAME&gt;Apple&lt;/NAME&gt;
     &lt;NAME&gt;Banana&lt;/NAME&gt;
    &lt;/RESULTS&gt;
    `)
        var r Results
    	decoder := xml.NewDecoder(bytes.NewBuffer(data))
    	unError := decoder.Decode(&amp;r)
	    if unError != nil {
		    fmt.Println(&quot;XML Unmarshaling error:&quot;, unError )
    	}else{
	    	fmt.Printf(&quot;%v&quot;, r)
	    }
    }

Tryed in the Playground, and locally (go1.17.2).


</details>


# 答案1
**得分**: 1

我建议你使用一个在线的结构体生成器比如[xmltogo][1]可以这样使用

```go
type RESULTS struct {
	XMLName xml.Name `xml:"RESULTS"`
	Text    string   `xml:",chardata"`
	NAME    []string `xml:"NAME"`
} 

在 playground 上试一试

英文:

I would suggest you to use a online struct generator like xmltogo, so use this as:

type RESULTS struct {
XMLName xml.Name `xml:&quot;RESULTS&quot;`
Text    string   `xml:&quot;,chardata&quot;`
NAME    []string `xml:&quot;NAME&quot;`
} 

Try on playground

huangapple
  • 本文由 发表于 2021年10月28日 20:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/69754186.html
匿名

发表评论

匿名网友

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

确定