xml - 如何从在线 xml 文件中解码 xml 数据

标签 xml go

假设我有一个 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.ReadAllxml.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/

相关文章:

xml - 当元素具有多于 1 个属性时的 DTD

python - 处理 xml 文档中缺失的元素

xml - 如何在 Silverlight 中计算 XPath 表达式?

java - 如何使用注释为 spring 设置 context.xml?

go - 如何从 Go 客户端获取 gRPC 服务器 IP

json - 如何检查 json 是否与结构/结构字段匹配

php - 如何仅使用 PHP 创建有效的 XML 树根元素?

go - 为什么 golang 有结构类型的值和指针

go - 我们可以在不构造 "manually"的情况下在数组和结构之间进行转换吗?

time - Go 的时间到底有多精确?