英文:
How to parse basic XML data which has one tag
问题
我可以解析复杂的XML结果,但在处理像这样返回简单答案的API时失败了。
xmlFile := <?xml version="1.0" encoding="utf-8" standalone="yes"?><TOKEN>C5F3DCFE370047ECAA9120F4E305B7D2</TOKEN>
我无法解析TOKEN。我尝试了各种方法,但无法弄清楚。我正在使用以下语法:
s := strings.Split(string(result),">")
s = strings.Split(s[2],"<")
b.Token = s[0]
<?xml version="1.0" encoding="utf-8" standalone="yes"?><TOKEN>C5F3DCFE370047ECAA9120F4E305B7D2</TOKEN>
如何解析这个(API还返回<?xml version="1.0" encoding="utf-8" standalone="yes"?><ERROR>an error</ERROR>
信息)
英文:
I can parse complex XML results but I fail at this simple thing which is api returning simple answers like this
xmlFile := <?xml version="1.0" encoding="utf-8" standalone="yes"?><TOKEN>C5F3DCFE370047ECAA9120F4E305B7D2</TOKEN>
I can't parse TOKEN. I tried everything but can't figure out. I'm using this syntax:
s := strings.Split(string(result),">")
s = strings.Split(s[2],"<")
b.Token = s[0]
<?xml version="1.0" encoding="utf-8" standalone="yes"?><TOKEN>C5F3DCFE370047ECAA9120F4E305B7D2</TOKEN>
how to parse this (also api returns <?xml version="1.0" encoding="utf-8" standalone="yes"?><ERROR>a error </ERROR>
informations)
答案1
得分: 2
用于解组分离的顶级元素,您可以实现自定义的解组器。
type Response struct {
Token string
Error string
}
func (r *Response) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
switch start.Name.Local {
case "TOKEN":
if err := d.DecodeElement(&r.Token, &start); err !=nil {
return err
}
case "ERROR":
if err := d.DecodeElement(&r.Error, &start); err !=nil {
return err
}
}
return nil
}
https://play.golang.org/p/OQy4ShS_vFx
英文:
For unmarshaling separate top-level elements you can implement a custom unmarshaler.
type Response struct {
Token string
Error string
}
func (r *Response) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
switch start.Name.Local {
case "TOKEN":
if err := d.DecodeElement(&r.Token, &start); err !=nil {
return err
}
case "ERROR":
if err := d.DecodeElement(&r.Error, &start); err !=nil {
return err
}
}
return nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论