亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將子元素的屬性直接解析為 Go 結構體

將子元素的屬性直接解析為 Go 結構體

Go
蠱毒傳說 2021-12-27 17:59:04
在使用 Go 解析 XML 時,如何將嵌套元素的屬性直接讀入結構中?我的 XML 如下所示。它是 OpenStreetMap 格式的一部分:<way id="123" >        <nd ref="101"/>        <!-- Lots of nd elements repeated -->        <nd ref="109"/></way>我有type Way struct {    Nodes []NodeRef `xml:"nd"`}和type NodeRef struct {    Ref int `xml:"ref,attr"`}但我希望能夠做到type Way struct {    Nodes []int `???`}直接地。關于解組的文檔對我沒有幫助。我試過使用,xml:"nd>ref,attr"但由于“鏈對 attr 標志無效”而失敗。
查看完整描述

1 回答

?
慕妹3146593

TA貢獻1820條經驗 獲得超9個贊

簡而言之,你不能直接這樣做。繞過 XML 結構的常見模式是實現xml.Unmarshaler接口。下面是一個例子:


type Way struct {

    ID    int 

    Nodes []int

}


func (w *Way) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {

    var payload struct {

        ID    int `xml:"id,attr"`

        Nodes []struct {

            Ref int `xml:"ref,attr"`

        } `xml:"nd"`

    }   


    err := d.DecodeElement(&payload, &start)

    if err != nil {

        return err 

    }   


    w.ID = payload.ID

    w.Nodes = make([]int, 0, len(payload.Nodes))


    for _, node := range payload.Nodes {

        w.Nodes = append(w.Nodes, node.Ref)

    }   


    return nil 

}

在這里,payload變量是根據您的 XML 數據建模的,而Way結構則是按照您希望的方式建模的。一旦有效載荷被解碼,您就可以使用它來根據需要初始化Way變量……


邊注: // Why can't I return nil, err?


您不能返回,nil因為Way它既不是指針也不是接口,因此nil不是它的有效值。


查看完整回答
反對 回復 2021-12-27
  • 1 回答
  • 0 關注
  • 2021 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號