1 回答
![?](http://img1.sycdn.imooc.com/545845d30001ee8a02200220-100-100.jpg)
TA贡献1784条经验 获得超8个赞
您的代码中有特定行返回错误
xml.Unmarshal(byteValue, &articles)
如果你把它改成
err = xml.Unmarshal(byteValue, &articles)
if err != nil {
fmt.Println(err.Error())
}
您会看到报告的错误:xml: encoding "ISO-8859-1" declared but Decoder.CharsetReader is nil。作为最佳实践,您应该始终检查返回的错误。
要解决此问题,您可以从 XML 中删除编码属性 ( encoding="ISO-8859-1") 或稍微更改解组代码:
package main
import (
"encoding/xml"
"fmt"
"io"
"os"
"golang.org/x/text/encoding/charmap"
)
// Contains the array of articles in the dblp xml
type Dblp struct {
XMLName xml.Name `xml:"dblp"`
Dblp []Article `xml:"article"`
}
// Contains the article element tags and attributes
type Article struct {
XMLName xml.Name `xml:"article"`
Key string `xml:"key,attr"`
Year string `xml:"year"`
}
func main() {
xmlFile, err := os.Open("dblp.xml")
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened TestDblp.xml")
// defer the closing of our xmlFile so that we can parse it later on
defer xmlFile.Close()
var articles Dblp
decoder := xml.NewDecoder(xmlFile)
decoder.CharsetReader = makeCharsetReader
err = decoder.Decode(&articles)
if err != nil {
fmt.Println(err)
}
for i := 0; i < len(articles.Dblp); i++ {
fmt.Println("Entered loop")
fmt.Println("get title: " + articles.Dblp[i].Key)
fmt.Println("get year: " + articles.Dblp[i].Year)
}
}
func makeCharsetReader(charset string, input io.Reader) (io.Reader, error) {
if charset == "ISO-8859-1" {
// Windows-1252 is a superset of ISO-8859-1, so should do here
return charmap.Windows1252.NewDecoder().Reader(input), nil
}
return nil, fmt.Errorf("Unknown charset: %s", charset)
}
运行上面的程序会导致:
Successfully Opened TestDblp.xml
Entered var
Entered loop
get title: journals/cacm/Gentry10
get year: 2010
Entered loop
get title: journals/cacm/Gentry10
get year: 2010
- 1 回答
- 0 关注
- 59 浏览
添加回答
举报