知道为什么这种解析在直接从站点访问 XML 时不起作用,而当我将其复制并粘贴到 var 时它起作用吗?
package main
import (
"encoding/xml"
"fmt"
"strings"
"io/ioutil"
"net/http"
)
type Sitemapindex struct {
Locations []Location `xml:"channel>item"`
}
type Location struct {
Loc string `xml:"title"`
}
func (e Location) String () string {
return fmt.Sprintf(e.Loc)
}
func main() {
resp, _ := http.Get("https://www.sec.gov/Archives/edgar/xbrlrss.all.xml")
bytes, _ := ioutil.ReadAll(resp.Body)
string_body := string(bytes)
var s Sitemapindex
decoder := xml.NewDecoder(strings.NewReader(string_body))
decoder.Strict = false
decoder.Decode(&s)
fmt.Println(s)
}
Run Code Online (Sandbox Code Playgroud)
您正在解析的内容被编码为windows-1252. 为了正确解码此数据,XML 解码器需要由可以读取指定字符集的字符集读取器进行参数化。
import (
"encoding/xml"
"golang.org/x/net/html/charset"
)
decoder := xml.NewDecoder(reader)
decoder.CharsetReader = charset.NewReaderLabel
err := decoder.Decode(&s)
Run Code Online (Sandbox Code Playgroud)
我猜想error您尝试解码数据时返回的内容会告诉您类似的信息。