普通网友 2018-03-27 09:12
浏览 437
已采纳

使用Go使用CDATA解析XML

I am new in Golang and I've been trying to parse an xml in Go by defining structs and using xml.Unmarshal.There's no error thrown but the struct is empty. this is my xml:

var bodyXML = []byte('<?xml version="1.0" encoding="ISO-8859-1"?>
<smsBatchResponse>
 <ok>
  <![CDATA[CHECK_OK]]>
 </ok>
</smsBatchResponse>')

and this is my code:

type SmsBatchResponse struct {
    Ok string `xml:"ok"`
}

var result SmsBatchResponse

xml.Unmarshal(bodyXML,result)
fmt.Println(result)
  • 写回答

1条回答 默认 最新

  • doucheng7234 2018-03-27 09:35
    关注

    The first thing you should do is not ignore any errors that xml.Unmarshal can give you:

    if err := xml.Unmarshal(bodyXML, result); err != nil {
        fmt.Println(err)
    }
    

    This will (eventually) give you a number of errors:

    Error number 1: By default, the XML decoder wants the XML to be encoded in UTF-8. You are providing ISO-8859-1. This can either be trivially fixed by changing your XML encoding to UTF-8; or by manually creating a xml.Decoder and settings the CharsetReader member.

    Error number 2: When unmarshalling, the XML decoder expects a pointer, because it needs to modify the passed in struct:

    if err := xml.Unmarshal(bodyXML, &result); err != nil {
        ....
    }
    

    Note the & in front of result.

    When you fix these errors, the XML unmarshals fine.

    I have created a fully working example on the Go Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料