[英]GOlang XML parsing / unmarshal
我在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
文档包含了很多示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.