我正在设置一个带有一些自定义元素的自定义 rss 提要。我需要添加一个带有自定义属性的自定义元素。
到目前为止,我已经设置了这样的提要:
var testItem = new SyndicationItem("title", "description", new Uri("http://myuri.com"));
customItem.ElementExtensions.Add("customElement", String.Empty, "fooBar");
将 testItem 添加到名为“items”的列表中,然后:
var feed = new SyndicationFeed("TestFeed", "FeedContent", new Uri("http://myuri.com"), items);
这会产生这样的东西......
<rss>
<channel>
<title>TestFeed</title>
<link>http://myuri.com</link>
<description>FeedContent</description>
<item>
<link>http://myprovider.com/contentid=1234</link>
<title>title</title>
<description>description</description>
<customElement>fooBar</customElement>
</item>
</channel>
</rss>
现在,如果我既要添加自定义元素,又要向该元素添加自定义属性怎么办?
我可以像这样创建一个新的 SyndicationItem:
var customElement = new SyndicationItem();
然后像这样给它添加属性:
customElement.AttributeExtensions.Add(new XmlQualifiedName("myAttribute", ""), "someValue");
customElement.AttributeExtensions.Add(new XmlQualifiedName("anotherAttribute"), "someOtherValue");
然后将它添加到我的 testItem 中,使其出现在我的 rss 提要项目列表中:
testItem.ElementExtensions.Add(customElement);
编译器吃掉了它,但我得到一个运行时错误,我认为这是因为新元素没有名称。
除此之外,我找不到其他方法
创建提要的 XmlDoc,然后开始向其附加元素和属性。
有必要这样做似乎很奇怪,我觉得我一定是监督了一些东西..
有什么想法吗?
最佳答案
找到解决方案。
我可以像这样向 Feed 添加项目:
var contentItem = new SyndicationItem("title", "description", new Uri("http://myuri.com"));
然后像这样向其中添加自定义元素:
contentItem.ElementExtensions.Add("customElement", String.Empty, "text inside my custom element");
如果我想添加自定义元素,并为其添加自定义属性;我能做到:
contentItem.ElementExtensions.Add(new XElement("customImageElement", new XAttribute("type", "image/jpg"), new XAttribute("url", "www.myuri.com/pic1234.jpg")).CreateReader());
这将输出:
<customImageElement type="image/jpg" url="www.myprovider.com/pic1234.jpg"></customImageElement>
完成后,我将 contentItem 添加到 List<SyndicationItem>
,并在我创建提要(项目)时添加此列表。
我还可以将自定义元素添加到提要本身,在 <channel>
下元素:
首先添加带有项目列表的提要:
var feed = new SyndicationFeed("title text", "description text", new Uri("http://myuri.com"), items);
然后将自定义元素添加到提要中。在元素下:
feed.ElementExtensions.Add(new XElement("image",
new XElement("url", null, "http://www.myuri.com/logo.jpg"),
new XElement("title", null, "MyImage"),
new XElement("link", null, "http://myuri.com/contentid=1234"),
new XElement("width", null, "100"),
new XElement("height", null, "100"),
new XElement("description", null, "This is my image")).CreateReader());
这将输出:
<rss version="2.0">
<channel>
<title>title text</title>
<link>http://myuri.com</link>
<description>description text</description>
<image>
<url>http://www.myprovider.com/logo.jpg</url>
<title>MyImage</title>
<link>http://myprovider.com/contentid=1234</link>
<width>100</width>
<height>100</height>
<description>This is my image</description>
</image>
<item>
Items added to the items collection
...
...
...
</item>
</channel>
</rss>
这就是我能想到的。如果有更好的方法,请分享。
关于c# - 具有自定义属性的自定义 RSS 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16796023/