雅虎新闻API在C#中

本文关键字:API 新闻 雅虎 | 更新日期: 2023-09-27 18:25:48

所以我正在用C#编写语音识别程序,当我试图将YAHOO News API实现到程序中时,我没有得到任何响应。

我不会复制/粘贴我的整个代码,因为它会很长,所以这里是主要的部分。

private void GetNews()
{
    string query = String.Format("http://news.yahoo.com/rss/");
    XmlDocument wData = new XmlDocument();
    wData.Load(query);
    XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
    manager.AddNamespace("media", "http://search.yahoo.com/mrss/");
    XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
    XmlNodeList nodes = wData.SelectNodes("rss/channel/item/description", manager);
    FirstStory = channel.SelectSingleNode("item").SelectSingleNode("title", manager).Attributes["alt"].Value;
}

我相信我做错了什么:

XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
XmlNodeList nodes = wData.SelectNodes("rss/channel/item/description", manager);
FirstStory = channel.SelectSingleNode("item").SelectSingleNode("title", manager).Attributes["alt"].Value;

以下是完整的XML文档:http://news.yahoo.com/rss/

如果需要更多信息,请告诉我。

雅虎新闻API在C#中

嗯,我已经实现了自己的代码来从雅虎获取新闻,我阅读了所有的新闻标题(位于rss/channel/item/Title)和短篇小说(位于rss/channel/iitem/description)。

短篇小说是新闻的问题,这就是我们需要在字符串中获取描述节点的所有内部文本,然后像XML一样解析它的时候。文本代码是这种格式的,短篇小说就在</p> 后面

<p><a><img /></a></p>"Short Story"<br clear="all"/>

我们需要修改它,因为我们有很多xml根(p和br),并且我们添加了一个额外的根<me>

string ShStory=null;
string Title = null;
//Creating a XML Document
XmlDocument doc = new XmlDocument();  
//Loading rss on it
doc.Load("http://news.yahoo.com/rss/");
//Looping every item in the XML
foreach (XmlNode node in doc.SelectNodes("rss/channel/item"))
{
    //Reading Title which is simple
    Title = node.SelectSingleNode("title").InnerText;
    //Putting all description text in string ndd
    string ndd =  node.SelectSingleNode("description").InnerText;
    XmlDocument xm = new XmlDocument();
    //Loading modified string as XML in xm with the root <me>
    xm.LoadXml("<me>"+ndd+"</me>");
    //Selecting node <p> which has the text
    XmlNode nodds = xm.SelectSingleNode("/me/p");
   //Putting inner text in the string ShStory
    ShStory= nodds.InnerText;
   //Showing the message box with the loaded data
    MessageBox.Show(Title+ "    "+ShStory); 
}

选择我作为正确答案,或者如果代码对你有效,请投票给我。如果有任何问题,你可以问我。干杯

很可能您正在将命名空间管理器传递给这些属性,但我不能100%确定。这些肯定不在.../mrss/命名空间中,所以我想这是您的问题。

我会在不传递名称空间(如果可能的话)或使用GetElementsByTagName方法来避免名称空间问题的情况下尝试它。

标记包含文本而不是Xml。以下是显示文本新闻的示例:

foreach (XmlElement node in nodes)
{
     Console.WriteLine(Regex.Match(node.InnerXml, 
                           "(?<=(/a&gt;)).+(?=(&lt;/p))"));
     Console.WriteLine();
}