英文:
golang - extract elements in xml string
问题
我想提取所有的loc
元素值,但是我得到了一个空数组。
我的代码:
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)
}
英文:
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
得分: 2
只有导出的字段和Caps字段才会被解组。此外,Loc
不应该是一个结构体,而可以直接是一个字符串。
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)
}
希望对你有帮助!
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论