如何解析只有一个标签的基本 XML 数据?

huangapple go评论85阅读模式
英文:

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 := &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; standalone=&quot;yes&quot;?&gt;&lt;TOKEN&gt;C5F3DCFE370047ECAA9120F4E305B7D2&lt;/TOKEN&gt;

I can't parse TOKEN. I tried everything but can't figure out. I'm using this syntax:

s := strings.Split(string(result),&quot;&gt;&quot;)
    s = strings.Split(s[2],&quot;&lt;&quot;)
    b.Token = s[0]

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; standalone=&quot;yes&quot;?&gt;&lt;TOKEN&gt;C5F3DCFE370047ECAA9120F4E305B7D2&lt;/TOKEN&gt; how to parse this (also api returns &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; standalone=&quot;yes&quot;?&gt;&lt;ERROR&gt;a error &lt;/ERROR&gt; 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 &quot;TOKEN&quot;:
		if err := d.DecodeElement(&amp;r.Token, &amp;start); err !=nil {
			return err
		}
	case &quot;ERROR&quot;:
		if err := d.DecodeElement(&amp;r.Error, &amp;start); err !=nil {
			return err
		}
	}
	return nil
}

https://play.golang.org/p/OQy4ShS_vFx

huangapple
  • 本文由 发表于 2021年10月29日 19:25:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/69768077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定