C#中的Yahoo News API

时间:2013-08-01 18:23:54

标签: c# xml yahoo-api

所以我正在使用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/

如果需要更多信息,请与我联系。

3 个答案:

答案 0 :(得分:1)

嗯,我已经实现了自己的代码来从雅虎获取新闻,我阅读了所有新闻标题(位于rss / channel / item / title)和短篇小说(位于rss / channel / item / 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); 
}

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

答案 1 :(得分:0)

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

我会尝试不传递命名空间(如果可能)或使用GetElementsByTagName方法来避免名称空间问题。

答案 2 :(得分:0)

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

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