GO中的XML Unmarshaling

时间:2018-04-06 05:37:48

标签: xml go

我有以下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>

现在,我会将它解组为golang结构,例如:

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解析器检测真正的标签数量,例如&#34; a&#34; in&#34; card&#34;。但它没有检测到这些属性的值。这是xml.Unmarshal之后的Printf输出:

 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:""}}}}

出了什么问题?

1 个答案:

答案 0 :(得分:3)

clientcard结构中的字段是私有的(具有小写名称),因此XML unmarshaler无法写入它们。将名称更改为以大写字母开头,它们将起作用。

此外,不相关,但您不需要cards结构只是为了让一个标签更深入。如果您在该图层没有其他任何内容,则可以添加

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

进入OwCheckClient结构并删除cards结构,它将正确反序列化。