我正在使用以下类型的XML结构
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title>TITLE</title>
<link>http://something.com</link>
<description>description</description>
<lastBuildDate>Mon, 19 Dec 2016 16:48:54 +0000</lastBuildDate>
<language>en</language>
<item>
<title>Title</title>
<description>description</description>
<author>
<name>Name</name>
<uri></uri>
</author>
<pubDate>Mon, 19 Dec 2016 16:42:32 +0000</pubDate>
<link>http://google.com</link>
<image>...</image>
<media:description><![CDATA[Natalie Massenet]]></media:description>
<media:credit>David Fisher/REX/Shutterstock</media:credit>
<category>Category1</category>
<category>Category2</category>
<guid isPermaLink="false">http://something.com/?p=10730393</guid>
<media:group></media:group>
<content:encoded>content</content:encoded>
</item>
</channel>
</rss>
我在弄清楚如何反序列化<description>
以及将其<media:description>
分解为结构中的两个不同元素时遇到了麻烦。
我尝试了以下一种结构体来表示<item>
,但是media:description
end 的值最终出现在该结构体中。
type Item struct {
// ...other fields
Description string `xml:"description"`
MediaDescription string `xml:"media:description"`
// ...other fields
}
最好的方法是什么?
因此,Go当前无法支持此功能(@JimB指出),但是您仍然可以使用一些内置功能来提取正确的元素。首先定义一个新的结构XMLElement
type XMLElement struct {
XMLName xml.Name
Data string `xml:",chardata"`
}
该结构可以捕获xml数据以及名称空间和元素名称。下一个映射xml:"description"
到的数组XMLElement
。最终将捕获<*:description>
列表中的所有元素。然后,您可以定义函数以提取正确的函数。
type Item struct {
// ...other fields
Descriptions []XMLElement `xml:"description"`
// ...other fields
}
// GetDescription returns the description in the <description> tag
func (i *Item) GetDescription() string {
for _, elem := range i.Descriptions {
if elem.XMLName.Space == "" {
return elem.Data
}
}
return ""
}
// GetMediaDescription returns the description in the <media:description> tag
func (i *Item) GetMediaDescription() string {
for _, elem := range i.Descriptions {
if elem.XMLName.Space == "http://search.yahoo.com/mrss/" {
return elem.Data
}
}
return ""
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句