无法解组具有值中包含空格的有效负载

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

Unable to Unmarshal a payload with spaces in values

问题

我正在使用Golang读取一个XML响应。我无法正确读取带有空格的值。

这是一个代码片段:https://gist.github.com/anonymous/5825288

有没有办法让xml.Unmarshal去掉<result>中的空格,然后将其作为整数处理?

例如:

<result>1<result> // 没有空格,被正确地解析。结构体中的结果值为1

但是

<result> 1 </result>  // 有空格,被错误地解析为整数。结构体中的结果值为0。
英文:

I am using Golang to read an XML response. I am unable to read values with spaces properly.

Here is a gist: https://gist.github.com/anonymous/5825288

Is there a way to have xml.Unmarshal trim the value from <result> and then treat it as an int?

I.e.

<result>1<result> // no spaces, is marshalled correctly.  The resulting value in the struct is 1

but

<result> 1 </result>  // with spaces, is marshalled incorrectly as an int.  The resulting value in the struct for result is 0.

答案1

得分: 4

即使在xml中,“1”是一个字符串而不是整数,解析器也无法将此字符串解析为整数。因此,0只是默认的整数值,

如果您将代码更改为:

err:= xml.Unmarshal([] byte(payload),&mt)
如果出现错误,则会看到解析期间发生错误
如果您的xml可能具有“1”作为值,我建议在您的结构中使用字符串。
或者如果有机会,告诉xml的创建者只使用整数而不是字符串,其中期望使用整数。

英文:

even in xml " 1 " this is a string and not a int,
the parser cant parse this string to an int. so 0 is just the default int value,

if you change your code to :

err:= xml.Unmarshal([]byte(payload), &mt)
if err != nil {
  fmt.Println(err)
}

you will see that there was an error during parsing
if your xml could have " 1 " as value, i recommend to use a string in your struct.
or if there is a chance, tell the creator of the xml to only use int and not strings, where int are expected

huangapple
  • 本文由 发表于 2013年6月21日 03:44:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/17222478.html
匿名

发表评论

匿名网友

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

确定