1 回答

TA貢獻1934條經(jīng)驗 獲得超2個贊
我將調(diào)試反饋放在評論中,但我剛剛修改了您的示例以使其正常工作,可以在此處進行測試;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使它們“導(dǎo)出”,以便其他包(在這種情況下為解組器)可以獲取/設(shè)置它們
3)添加xml屬性。在導(dǎo)出字段時,它使它沒有隱式字符串匹配,因此您必須明確指定將哪個 xml 值讀入每個字段
4)BookList為此更新 XML 路徑,您說它將是 Books>Book 但這意味著您的 xml 中不存在另一個嵌套級別。這個對象是Books,您想要在該列表中的元素將具有簡單的相對 xpath,Book這就是您放置在那里的內(nèi)容。
- 1 回答
- 0 關(guān)注
- 280 瀏覽
添加回答
舉報