我一定遺漏了一些非常明顯的東西......我正在嘗試解析一個簡單的 XML 文件,按照ExampleUnmarshal()這里的示例:http : //golang.org/src/pkg/encoding/xml/example_test.go正如您將在本文底部看到的,沒有任何屬性或子元素被映射 - 無論是方向 - Marshal 還是 Unmarshal。據我所知,這幾乎與他們在上面的 example_test.go 中所做的完全相同(我能看到的唯一區別是該測試中的類型在函數的范圍內 - 我嘗試過,沒有區別,并且他們使用子元素而不是屬性 - 除了id- 但每個文檔名稱,attr 應該工作 afaict)。代碼如下所示:package mainimport ( "fmt" "encoding/xml" "io/ioutil")type String struct { XMLName xml.Name `xml:"STRING"` lang string `xml:"lang,attr"` value string `xml:"value,attr"`}type Entry struct { XMLName xml.Name `xml:"ENTRY"` id string `xml:"id,attr"` strings []String }type Dictionary struct { XMLName xml.Name `xml:"DICTIONARY"` thetype string `xml:"type,attr"` ignore string `xml:"ignore,attr"` entries []Entry }func main() { dict := Dictionary{} b := []byte(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><DICTIONARY type="multilanguage" ignore="en"> <ENTRY id="ActionText.Description.AI_ConfigureChainer"> <STRING value="ActionText.Description.AI_ConfigureChainer"/> <STRING value=""/> <STRING value=""/> <STRING value=""/> </ENTRY></DICTIONARY>`) err := xml.Unmarshal(b, &dict) if err != nil { panic(err) } fmt.Println(dict) // prints: {{ DICTIONARY} []} dict.ignore = "test" out, err := xml.MarshalIndent(&dict, " ", " ") fmt.Println(string(out)) // prints: <DICTIONARY></DICTIONARY> // huh?}
1 回答

森欄
TA貢獻1810條經驗 獲得超5個贊
您需要導出(大寫)您的結構字段。
從encoding/xml
Marshall
功能文檔:
結構的 XML 元素包含結構的每個導出字段的編組元素
有關相關答案,請參閱無法在 golang 中解析復雜的 json。
- 1 回答
- 0 關注
- 277 瀏覽
添加回答
舉報
0/150
提交
取消