dszm02606009 2019-05-09 10:54
浏览 49
已采纳

Golang无法将XML映射到Struct

I want to map XML data to Struct object. I have following code:

package main
import (
    "encoding/xml"
    "fmt"
)

func main() {
    type FileDetails struct {
        XMLName   xml.Name `xml:"FileDetails"`
        FileName string
        FileSize string
    }

    type DataRequest struct {
        XMLName   xml.Name `xml:"Data"`
        DataRequestList []FileDetails
    }

    type Request struct {
        XMLName   xml.Name `xml:"Request"`
        DataReqObject DataRequest `xml:"Data"`
    }
    req := Request{}

    data := `
        <Request>
            <Data>
                <FileDetails>
                    <FileName>abc</FileSize>
                    <FileSize>10</FileSize>
                </FileDetails>
                <FileDetails>
                    <FileName>pqr</FileSize>
                    <FileSize>20</FileSize>
                </FileDetails>
            </Data>
        </Request>
    `
    err := xml.Unmarshal([]byte(data), &req)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Printf("XMLName: %#v
", req.XMLName)
    fmt.Printf("XMLName: %v
", req.DataReqObject)
    fmt.Printf("XMLName: %v
", req.DataReqObject.DataRequestList[0])
}

This can also be accessed here: https://play.golang.org/p/VAMM9M2CejH

I'm getting following output with the above code:

XMLName: xml.Name{Space:"", Local:"Request"}
Data: {{ Data} []}
panic: runtime error: index out of range

Do the structs need to have diffferent structure for my data? Why is this mapping failing?

  • 写回答

1条回答 默认 最新

  • douzi9211 2019-05-09 11:11
    关注

    Three problems with your snippet:

    #1

    The tag xml:"FileDetails" is missing on DataRequestList


    #2

    The FileDetails struct does not match your xml in the provided playground link!


    #3

    <FileName> tag is closed with </FileSize> tag!


    Go playground working example!

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

报告相同问题?

悬赏问题

  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析