dragam0217 2013-07-10 13:42
浏览 50

如果字段为空,则避免XML整数解析错误

Consider these 2 XML documents

<a>
  <b nil="true"></b>
</a>

and

<a>
  <b type="integer">1</b>
</a>

How can I unmarshal this XML properly in Go to a b struct field of type int, without producing a strconv.ParseInt: parsing "": invalid syntax error in the first case?

omitempty doesn't seem to work in this case.

Example: http://play.golang.org/p/fbhVJ4zUbl

  • 写回答

2条回答 默认 最新

  • duankeng9477 2013-07-10 19:39
    关注

    The omitempty tag is just respected with Marshal, not Unmarshal.

    Unmarshal errors if the int value is not an actual int.

    Instead, change B to a string. Then, convert B to an int with the strconv package. If it errors, set it to 0.

    Try this snippet: http://play.golang.org/p/1zqmlmIQDB

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等