英文:
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't work as expected.
It just returns a `{[]}` empty `Results`, while it should fill it.
Why ?...
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)
}
}
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"`
}
英文:
I would suggest you to use a online struct generator like xmltogo, so use this as:
type RESULTS struct {
XMLName xml.Name `xml:"RESULTS"`
Text string `xml:",chardata"`
NAME []string `xml:"NAME"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论