dongwanqiang_2017 2018-04-06 05:37
浏览 54
已采纳

GO中的XML解组

I have the following XML

<a>
    <client client_id="6881937" clt_code="0" clt_date="" sms_block="N" active_serv="N" phone="77777645521" threshold_amount="1" clt_charge="" clt_charge_id="" > </client> 
    <card> 
        <a card_num="KZ5392...6449" card_id="66783573" crd_code="0" crd_date="" />
        <a card_num="552204...9124" card_id="66783574" crd_code="0" crd_date="" />
        <a card_num="KZ7392...4128" card_id="14335135" crd_code="0" crd_date="" />
        <a card_num="440564...7683" card_id="14335136" crd_code="0" crd_date="" />
     </card>
</a>

Now, I would unmarshal it into the golang struct such as:

type OwCheckClient struct {
    XMLName xml.Name `xml:"a"`
    Client client `xml:"client"`
    Cards cards `xml:"card"`
}

type client struct {
    client_id string  `xml:"client_id,attr"`
    clt_code string `xml:"clt_code,attr"`
    sms_block string `xml:"sms_block,attr"`
    active_serv string `xml:"active_serv,attr"`
    phone string `xml:"phone,attr"`
    threshold_amount string `xml:"threshold_amount,attr"`
    clt_charge string `xml:"clt_charge,attr"`
    clt_charge_id string `xml:"clt_charge_id,attr"`
}

type cards struct {
    Card []card `xml:"a"`
}

type card struct {
    card_num string `xml:"card_num,attr"`
    card_id string `xml:"card_id,attr"`
    crd_code string `xml:"crd_code,attr"`
}

XML parser detects true amount of tags,for instance, "a" in "card". But it doesn't detect values of these attributes. That is Printf output below after xml.Unmarshal:

 v = &models.OwCheckClient{XMLName:xml.Name{Space:"", Local:"a"}, Client:models.client{client_id:"", clt_code:"", sms_block:"", active_serv:"", phone:"", threshold_amount:"", clt_charge:"", clt_charge_id:""}, Cards:models.cards{Card:[]models.card{models.card{card_num:"", card_id:"", crd_code:""}, models.card{card_num:"", card_id:"", crd_code:""}, models.card{card_num:"", card_id:"", crd_code:""}, models.card{card_num:"", card_id:"", crd_code:""}}}}

What's wrong?

  • 写回答

1条回答 默认 最新

  • dt2002 2018-04-06 06:31
    关注

    The fields in the client and card structs are private (have lowercase names), so the XML unmarshaler can't write to them. Change the names to start with an uppercase letter and they will work.

    Also, unrelated, but you don't need the cards struct just to get one tag deeper. If there's nothing else you need at that layer, you can put

    Cards []card `xml:"card>a"`
    

    into your OwCheckClient struct and delete the cards struct and it will deserialize properly.

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

报告相同问题?

悬赏问题

  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥85 maple软件,solve求反函数,出现rootof怎么办?
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题