英文:
Building MRSS feed in Go
问题
我正在尝试获取结果:
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss">
使用以下代码:
type RSS struct {
XMLName xml.Name `xml:"rss"`
Xmlns string `xml:"xmlns:media,attr"`
Version string `xml:"version,attr"`
Channel Channel `xml:"channel"`
}
rss := &RSS{Version: "2.0", Xmlns:media: "http://search.yahoo.com/mrss"}
但是由于冒号的存在,我遇到了语法错误。如果没有":media",就没有错误。我该如何添加它?谢谢。
英文:
Im trying to get the result:
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss">
with:
type RSS struct {
XMLName xml.Name `xml:"rss"`
Xmlns string `xml:"xmlns:media,attr"`
Version string `xml:"version,attr"`
Channel Channel `xml:"channel"`
}
rss := &RSS{Version: "2.0", Xmlns:media: "http://search.yahoo.com/mrss"}
But I get a syntax error because of the colon. Without the ":media" there are no errors. How can I add that? Thanks.
答案1
得分: 2
你已经完成了使其工作所需的一切,只是你的复合字面量写错了,你使用的是xml属性名而不是字段名。注释的主要原因之一是为了在字段名上提供灵活性,原因很明显,比如小写字段不受支持,而且json和xml的命名规则与Go不一致。以下是你代码的一个可工作示例:
type RSS struct {
XMLName xml.Name `xml:"rss"`
Xmlns string `xml:"xmlns:media,attr"`
Version string `xml:"version,attr"`
Channel Channel `xml:"channel"`
}
rss := &RSS{Version: "2.0", Xmlns: "http://search.yahoo.com/mrss"}
英文:
You've already done everything necessary to make it work, your composite literal is just wrong, you're using the xml attribute name rather than the field name. One of the main reason for annotation is to provide flexibility on your field names for some obvious reasons like the fact that lower cased fields aren't supported and the naming rules for json and xml aren't consistent with Go. Here is a working example of your code;
type RSS struct {
XMLName xml.Name `xml:"rss"`
Xmlns string `xml:"xmlns:media,attr"`
Version string `xml:"version,attr"`
Channel Channel `xml:"channel"`
}
rss := &RSS{Version: "2.0", Xmlns: "http://search.yahoo.com/mrss"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论