Golang Google警报XML解析

huangapple go评论115阅读模式
英文:

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 :

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;feed 
    xmlns=&quot;http://www.w3.org/2005/Atom&quot; 
    xmlns:idx=&quot;urn:atom-extension:indexing&quot;&gt;
    
    &lt;entry&gt;
        &lt;title type=&quot;html&quot;&gt;Some Title&lt;/title&gt;
        &lt;link href=&quot;https://www.google.com&quot;&gt;&lt;/link&gt;
    &lt;/entry&gt;
&lt;/feed&gt;

I want to parse Each &lt;entry&gt; with its &lt;title&gt;& &lt;link&gt; tag so far I have successfully parsed the title but no success with &lt;link&gt;.

My Code :

type Entry struct {
	XMLName xml.Name `xml:&quot;entry&quot;`
	Link    string   `xml:&quot;link&quot;`
	Title   string   `xml:&quot;title&quot;`
}

type Feed struct {
	XMLName xml.Name `xml:&quot;feed&quot;`
	Entries []Entry  `xml:&quot;entry&quot;`
}

func (s Entry) String() string {
	return fmt.Sprintf(&quot;\t Link : %s - Title : %s \n&quot;, 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 &lt;link&gt; but it is the value of its attribute &quot;href&quot;.

You can extract the value of the attribute with the following code:

type Link struct {
	Href string `xml:&quot;href,attr&quot;`
}

And your modified Entry type:

type Entry struct {
	XMLName xml.Name `xml:&quot;entry&quot;`
	Link    Link     `xml:&quot;link&quot;`
	Title   string   `xml:&quot;title&quot;`
}

Try your modified app on the Go Playground.

huangapple
  • 本文由 发表于 2015年3月4日 23:08:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/28857837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定