假设我有一个 xml 文件 https://www.notre-shop.com/sitemap_products_1.xml我想在我的 go 代码中解码这个 xml,所以我这样做了
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"net/http"
)
var Product struct {
Locs []string `xml:"url>loc"`
Name []string `xml:"url>image:title"`
}
func main() {
res, err := http.Get("https://www.notre-shop.com/sitemap_products_1.xml")
if err!=nil{
log.Fatal(err)
}
data, err := ioutil.ReadAll(res.Body)
if err!=nil{
log.Fatal(err)
}
defer res.Body.Close()
err = xml.Unmarshal(data, &Product)
if err!=nil{
log.Fatal(err)
}
for x, _ := range Product.Name {
fmt.Println(Product.Name[x], Product.Locs[x])
}
}
但这不会打印任何内容。我做错了什么?
这是完整的代码https://play.golang.org/p/pZ6j4-lSEz正在播放。
最佳答案
请尝试以下对我有用的代码(注意:您也可以像以前一样使用 ioutil.ReadAll
和 xml.Unmarshal
,而不是 xml.解码
):
package main
import (
"encoding/xml"
"fmt"
"log"
"net/http"
)
// <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
// <url>
// <loc>
// https://www.notre-shop.com/products/test-product-releasing-soon-2
// </loc>
// <lastmod>2017-01-17T08:04:44Z</lastmod>
// <changefreq>daily</changefreq>
// <image:image>
// <image:loc>
// https://cdn.shopify.com/s/files/1/0624/0605/products/NOTRE-CHICAGO-QK9C9548_fde37b05-495e-47b0-8dd1-b053c9ed3545.jpg?v=1481853712
// </image:loc>
// <image:title>Test Product Releasing Soon 2</image:title>
// </image:image>
// </url>
// </urlset>
type URLSet struct {
XMLName string `xml:"urlset"`
URLs []URL `xml:"url"`
}
type URL struct {
Loc string `xml:"loc"`
Image Image `xml:"image"`
}
type Image struct {
Title string `xml:"title"`
}
func main() {
resp, err := http.Get("https://www.notre-shop.com/sitemap_products_1.xml")
if err != nil {
log.Fatalln(err) // log.Fatal always exits the program, need to check err != nil first
}
defer resp.Body.Close()
var urlSet URLSet
if err = xml.NewDecoder(resp.Body).Decode(&urlSet); err != nil {
log.Fatalln(err)
}
for _, url := range urlSet.URLs {
fmt.Println(url.Loc, url.Image.Title)
}
}
关于xml - 如何从在线 xml 文件中解码 xml 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41821088/