无法为 Go 结构解组 XML

我正在尝试在 golang 中编写一段代码,它需要一个 xml 并对其进行解组。我很确定我在结构的最后做错了什么,但我不知道是什么。因此,如果有人能告诉我为什么打印的价格没有任何价值,以及如何解决这个问题,我将不胜感激。非常感谢!


package main


import (

    "encoding/xml"

    "fmt"

    "log"

)


type DataSet struct {

    XMLName     xml.Name    `xml:"DataSet"`

    Header      Header      `xml:"Header"`

    Body        Body        `xml:"Body"`

}


type Header struct {

    XMLName         xml.Name    `xml:"Header"`

    Publisher       string      `xml:"Publisher"`

    PublishingDate  string      `xml:"PublishingDate"`

    MessageType     string      `xml:"MessageType"`

}


type Body struct {

    XMLName         xml.Name    `xml:"Body"`

    Subject         string      `xml:"Subject"`

    OrigCurrency    string      `xml:"OrigCurrency"`

    Cube            Cube        `xml:"Cube"`

}


type Cube struct {

    XMLName         xml.Name    `xml:"Cube"`

    Date            string      `xml:"date,attr"`

    Rate            []Rate      `xml:"Rate"`

}


type Rate struct {

    XMLName         xml.Name    `xml:"Rate"`

    Currency        string      `xml:"currency,attr"`

    Rate            string      `xml:"Rate"`

}


func main() {

    myxml := `<DataSet xmlns="http://www.bnr.ro/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.bnr.ro/xsd nbrfxrates.xsd">

    <Header>

        <Publisher>National Bank of Romania</Publisher>

        <PublishingDate>2020-05-07</PublishingDate>

        <MessageType>DR</MessageType>

    </Header>

    <Body>

        <Subject>Reference rates</Subject>

        <OrigCurrency>RON</OrigCurrency>

        <Cube date="2020-05-07">

            <Rate currency="AED">1.2169</Rate>

        </Cube>

    </Body>

</DataSet>`



红糖糍粑
浏览 64回答 1
1回答

潇潇雨雨

尝试将Rate结构更改为此:type Rate struct {&nbsp; &nbsp; XMLName&nbsp; &nbsp; xml.Name `xml:"Rate"`&nbsp; &nbsp; Currency&nbsp; &nbsp;string&nbsp; &nbsp;`xml:"currency,attr"`&nbsp; &nbsp; Multiplier string&nbsp; &nbsp;`xml:"multiplier,attr"`&nbsp; &nbsp; Rate&nbsp; &nbsp; &nbsp; &nbsp;string&nbsp; &nbsp;`xml:",chardata"`}而且我经常使用这个站点将XML转换为Go struct。你也可以试试:https ://www.onlinetool.io/xmltogo/
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go