英文:
Golang Google alert XML parse
问题
我的XML数据:
<?xml version="1.0" encoding="utf-8"?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:idx="urn:atom-extension:indexing">
<entry>
<title type="html">Some Title</title>
<link href="https://www.google.com"></link>
</entry>
</feed>
我想解析每个<entry>
标签及其<title>
和<link>
标签,到目前为止,我已成功解析了标题,但无法成功解析<link>
。
我的代码:
type Entry struct {
XMLName xml.Name `xml:"entry"`
Link string `xml:"link>href"`
Title string `xml:"title"`
}
type Feed struct {
XMLName xml.Name `xml:"feed"`
Entries []Entry `xml:"entry"`
}
func (s Entry) String() string {
return fmt.Sprintf("\t Link : %s - Title : %s \n", s.Link, s.Title)
}
演示链接:http://play.golang.org/p/hteQ5RuMco
英文:
My XML data :
<?xml version="1.0" encoding="utf-8"?>
<feed
xmlns="http://www.w3.org/2005/Atom"
xmlns:idx="urn:atom-extension:indexing">
<entry>
<title type="html">Some Title</title>
<link href="https://www.google.com"></link>
</entry>
</feed>
I want to parse Each <entry>
with its <title>
& <link>
tag so far I have successfully parsed the title but no success with <link>
.
My Code :
type Entry struct {
XMLName xml.Name `xml:"entry"`
Link string `xml:"link"`
Title string `xml:"title"`
}
type Feed struct {
XMLName xml.Name `xml:"feed"`
Entries []Entry `xml:"entry"`
}
func (s Entry) String() string {
return fmt.Sprintf("\t Link : %s - Title : %s \n", s.Link, s.Title)
}
Live demo at http://play.golang.org/p/hteQ5RuMco
答案1
得分: 3
你离答案很近了。你的代码没有提取链接的URL,因为它不是<link>
元素的值,而是它的属性"href"
的值。
你可以使用以下代码提取属性的值:
type Link struct {
Href string `xml:"href,attr"`
}
type Entry struct {
XMLName xml.Name `xml:"entry"`
Link Link `xml:"link"`
Title string `xml:"title"`
}
在Go Playground上尝试修改后的应用程序。
英文:
You're close. Your code doesn't extract the link URL because it is not the value of the element <link>
but it is the value of its attribute "href"
.
You can extract the value of the attribute with the following code:
type Link struct {
Href string `xml:"href,attr"`
}
And your modified Entry
type:
type Entry struct {
XMLName xml.Name `xml:"entry"`
Link Link `xml:"link"`
Title string `xml:"title"`
}
Try your modified app on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论