1 回答
TA贡献1934条经验 获得超2个赞
我将调试反馈放在评论中,但我刚刚修改了您的示例以使其正常工作,可以在此处进行测试;https://play.golang.org/p/_UIph2je7f
package main
import (
"fmt"
//"io/ioutil"
"encoding/xml"
)
func check(e error) {
if e != nil {
panic(e)
}
}
type Books struct {
XMLName xml.Name `xml:"Books"`
BookList []Book `xml:"Book"`
}
type Book struct {
Title string `xml:"title,attr"`
Author string `xml:"author,attr"`
Published string `xml:"published,attr"`
}
func main() {
//f, err := ioutil.ReadFile("xml/Books.xml")
//check(err)
var data = []byte(`
<Books>
<Book title="A Brief History of Time" author="Stephen Hawking" published="1988">
<title>title here</title>
A Brief History of Time: From the Big Bang to Black Holes is a 1988 popular-science book by British physicist Stephen Hawking. It became a bestseller and sold more than 10 million copies in 20 years.
</Book>
<Book title="Steve Jobs" author="Walter Isaacson" published="2011">
Steve Jobs is the authorized self-titled biography book of Steve Jobs. The book was written at the request of Jobs by Walter Isaacson, a former executive at CNN.
</Book>
</Books>
`)
b := Books{}
o := xml.Unmarshal([]byte(data), &b)
fmt.Println(o)
fmt.Println(b)
}
这是我所做的四项更改的概要;
1)打印Books对象而不是从返回的错误Unmarshal
2)大写字段的第一个字母,Book使它们“导出”,以便其他包(在这种情况下为解组器)可以获取/设置它们
3)添加xml属性。在导出字段时,它使它没有隐式字符串匹配,因此您必须明确指定将哪个 xml 值读入每个字段
4)BookList为此更新 XML 路径,您说它将是 Books>Book 但这意味着您的 xml 中不存在另一个嵌套级别。这个对象是Books,您想要在该列表中的元素将具有简单的相对 xpath,Book这就是您放置在那里的内容。
- 1 回答
- 0 关注
- 257 浏览
添加回答
举报