我在 Go 中解析 xml 时遇到问题。谁能帮忙? XML 格式为:
<Feed version='1.03' format='FULL' date='2016-04-22T18:31:01.4988282+01:00'>
<Ids>
<Id code='000001' quantity='4' />
<Id code='000002' quantity='0' />
</Ids>
</Feed>
最佳答案
对于任何想知道的人,这里有一个示例,它将往返提到的 XML 以进行结构和返回:
func TestXml(t *testing.T) {
type Id struct {
Code string `xml:"code,attr"`
Quantity int `xml:"quantity,attr"`
}
type Feed struct {
Version string `xml:"version,attr"`
Format string `xml:"format,attr"`
Date string `xml:"date,attr"`
Ids []Id `xml:"Ids>Id"`
}
x := []byte(`
<Feed version='1.03' format='FULL' date='2016-04-22T18:31:01.4988282+01:00'>
<Ids>
<Id code='000001' quantity='4' />
<Id code='000002' quantity='0' />
</Ids>
</Feed>
`)
f := Feed{}
xml.Unmarshal(x, &f)
t.Logf("%#v", f)
t.Log("Code 0:", f.Ids[0].Code)
b, _ := xml.Marshal(f)
t.Log(string(b))
}
这会产生以下输出:
xml_test.go:42: domain.Feed{Version:"1.03", Format:"FULL", Date:"2016-04-22T18:31:01.4988282+01:00", Ids:[]domain.Id{domain.Id{Code:"000001", Quantity:4}, domain.Id{Code:"000002", Quantity:0}}}
xml_test.go:43: Code 0: 000001
xml_test.go:46: <Feed version="1.03" format="FULL" date="2016-04-22T18:31:01.4988282+01:00"><Ids><Id code="000001" quantity="4"></Id><Id code="000002" quantity="0"></Id></Ids></Feed>
xml
的文档包含很好的例子。
关于xml - Golang XML 解析/解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36825597/