dongwang788787 2015-04-16 09:22
浏览 191
已采纳

golang-提取xml字符串中的元素

I want to extract all loc element value but I am getting an empty array

My code:

package main

import (
    "fmt"
    "encoding/xml"
)

type Query struct {
    XMLName xml.Name `xml:"urlset"`
    locs []Loc `xml:"url>loc"`
}

type Loc struct {
    loc string 
}

var data = []byte(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
   <loc>http://www.konga.com/mobile-recharge</loc>
   <lastmod>2015-04-14</lastmod>
   <changefreq>daily</changefreq>
   <priority>0.5</priority>
</url>
<url>
   <loc>http://www.konga.com/beauty-health-personal-care</loc>
   <lastmod>2015-04-14</lastmod>
   <changefreq>daily</changefreq>
   <priority>0.5</priority>
</url>
</urlset>`)


func main() {

    var q Query
    xml.Unmarshal(data, &q)
    fmt.Println(q.locs)
}
  • 写回答

1条回答 默认 最新

  • dongzhang1839 2015-04-16 09:32
    关注

    It only unmarshals exported and thus Caps fields. Also Loc shouldn't be a struct but can be a string directly.

    package main
    
    import (
        "encoding/xml"
        "fmt"
    )
    
    type Query struct {
        XMLName xml.Name `xml:"urlset"`
        Locs    []Loc    `xml:"url>loc"`
    }
    
    type Loc string
    
    var data = []byte(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
       <loc>http://www.konga.com/mobile-recharge</loc>
       <lastmod>2015-04-14</lastmod>
       <changefreq>daily</changefreq>
       <priority>0.5</priority>
    </url>
    <url>
       <loc>http://www.konga.com/beauty-health-personal-care</loc>
       <lastmod>2015-04-14</lastmod>
       <changefreq>daily</changefreq>
       <priority>0.5</priority>
    </url>
    </urlset>`)
    
    func main() {
    
        var q Query
        xml.Unmarshal(data, &q)
        fmt.Println(q.Locs)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog