how to golang Unmarshal a xml message into a struct

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

how to golang Unmarshal a xml message into a struct

问题

如何解码这个 XML?

<?xml version="1.0" encoding="UTF-8"?>
<LocationConstraint>oss-cn-hangzhou</LocationConstraint>

我的代码如下:

type BucketLocation struct {
    LocationConstraint string `xml:"LocationConstraint"`
}
v := &BucketLocation{}
xml.Unmarshal(xml_content, v)

但是它不起作用。

英文:

how to decode this xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;LocationConstraint&gt;oss-cn-hangzhou&lt;/LocationConstraint&gt;

my code is like this:

type BucketLocation struct {
	LocationConstraint string `xml:&quot;LocationConstraint&quot;`
}
v := &amp;BucketLocation{}
xml.Unmarshal(xml_content, v)

but it does not work.

答案1

得分: 3

你的结构体定义暗示了以下的 XML 格式,但与你提供的内容不匹配:

<BucketLocation>
    <LocationConstraint>oss-cn-hangzhou</LocationConstraint>
</BucketLocation>

要读取你给出的示例 XML,你可以这样做:

var v string
xml.Unmarshal(xml_content, &v)
英文:

The definition of your struct implies the following XML format which doesn't match what you're providing:

&lt;BucketLocation&gt;
    &lt;LocationConstraint&gt;oss-cn-hangzhou&lt;/LocationConstraint&gt;
&lt;/BucketLocation&gt;

To read the example XML that you've given you would do something this:

var v string
xml.Unmarshal(xml_content, &amp;v)

huangapple
  • 本文由 发表于 2015年10月28日 11:52:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/33382610.html
匿名

发表评论

匿名网友

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

确定