我想让这个工作
我正在使用this code并且它本身可以正常工作,但现在我想要读取以下元素:dc:creator并且无法使用。
类文件:
public class RSSItem
{
XNamespace dc="http://purl.org/dc/elements/1.1/";
public string Title { get; set; }
public string Description { get; set; }
public string PubDate { get; set; }
public string Link { get; set; }
public string strGuid { get; set; }
public string Author { get; set; }
public string Dc_creator { get; set; }
// Next we’ll modify the constructor. First add a parameter list to the constructor:
public RSSItem(string title, string description, string link, string guid,
string pubDate, string (dc:creator) //<-- not working but what to use instead)
{
// This constructor will be used to parse the RSS xml. Add the following code to the constructor:
Title = title;
Description = description;
Link = link;
strGuid = guid;
PubDate = pubDate;
Dc_creator = dc:creator; <-- not working but what to use instead
显然这不起作用:
string (dc:creator)) in the constructor
page.cshtml:
<div>
@{
XNamespace dc = XNamespace.Get("http://purl.org/dc/elements/1.1/");
XDocument rss = XDocument.Load("http://rss.xml");
var items = from elem in rss.Elements("rss").Elements("channel").Elements("item")
select elem;
foreach (var item in items)
{
RSSItem rssItem = new RSSItem(
item.Element("title").Value,
item.Element("link").Value,
item.Element("guid").Value,
item.Element("description").Value,
//item.Element("author").Value,
item.Element("pubDate").Value,
item.Element(dc + "creator").Value
);
<span class="rssStyle">
<div>
<b>@rssItem.Title</b>
</div>
etc etc
那么如何让类构造函数读取dc:creator
元素?
答案 0 :(得分:0)
不是确切的解决方案,但我使用XmlDocument
完成了此操作。你必须根据你的RssItem
修改它,我有类似的对象
XmlDocument doc = new XmlDocument();
doc.LoadXml(rss);
//Get Channel Node
XmlNode channelNode = doc.SelectSingleNode("rss/channel");
if (channelNode != null) {
//Add NameSpace
XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
nameSpace.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
nameSpace.AddNamespace("slash", "http://purl.org/rss/1.0/modules/slash/");
nameSpace.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
//Parse each item
foreach (XmlNode itemNode in channelNode.SelectNodes("item")) {
RssFeed rssItem = new RssFeed();
rssItem.Guid = itemNode.SelectSingleNode("guid").InnerText;
rssItem.Title = itemNode.SelectSingleNode("title").InnerText;
rssItem.CreatedBy = itemNode.SelectSingleNode("dc:creator", nameSpace).InnerText;
rssItem.Url = itemNode.SelectSingleNode("link").InnerText;
rssItem.PubDate = DateTime.Parse(itemNode.SelectSingleNode("pubDate").InnerText);
rssItem.CommentCount = itemNode.SelectSingleNode("slash:comments", nameSpace).InnerText;
rssItem.Description = itemNode.SelectSingleNode("content:encoded", nameSpace).InnerText;
}
}