Golang HTTP XML解析问题

时间:2016-10-02 10:11:36

标签: xml http parsing go

我正在尝试访问在线提供的XML文件,但在GET之后,XML格式消失了 我做错了什么?
非常感谢你!

func getHttp(address string) string{
    resp, err := http.Get(address)
    resp.Header.Add("Content-Type","application/xml; charset=utf-8")
    if err != nil {
        panic(err)
    }

    defer resp.Body.Close()

    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    return (string(data))
}

新格式如下所示:

{"SessionKey":"229eaeaa9fb14a0d85ff38ae4e0c7870_ecilpojl_018FC93424D13ECC0908CE5BC5E3F86B","Query":{"Country":"GB","Currency":"GBP","Locale":"en-gb","Adults":1,"Children":0,"Infants":0,"OutboundDate":"2016-10-08","LocationSchema":"Default","CabinClass":"Economy","GroupPricing":false},

而不是

<SessionKey>229eaeaa9fb14a0d85ff38ae4e0c7870_ecilpojl_018FC93424D13ECC0908CE5BC5E3F86B</SessionKey>
  <Query>
    <Country>GB</Country>
    <Currency>GBP</Currency>
    <Locale>en-gb</Locale>
    <Adults>1</Adults>
    <Children>0</Children>
    <Infants>0</Infants>
    <OutboundDate>2016-10-08</OutboundDate>
    <LocationSchema>Default</LocationSchema>
    <CabinClass>Economy</CabinClass>
    <GroupPricing>false</GroupPricing>
  </Query>

1 个答案:

答案 0 :(得分:1)

请参阅: GetSystemDefaultLangID(void)

试试这个(并用你的网址替换):

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    fmt.Println(getHttp(`http://stackoverflow.com/`))
}
func getHttp(url string) string {    
    client := &http.Client{}
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        panic(err)
    }
    req.Header.Set("ACCEPT", "application/xhtml+xml,application/xml")
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    return string(data)
}

我希望这会有所帮助。