【问题标题】:Reading XML with a colon (:)使用冒号 (:) 读取 XML
【发布时间】:2014-05-18 15:08:25
【问题描述】:

我正在尝试从以下 XML 文档 (https://gdata.youtube.com/feeds/api/videos?q=example) 中获取视频的观看次数,因为标签中没有冒号,所以我能够获取链接和作者。

我正在尝试获取 yt:statistics 但我不知道如何。

    result = e.Result.Replace("xmlns='http://www.w3.org/2005/Atom' ", String.Empty);

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(result);

    XmlNodeList videos = doc.GetElementsByTagName("entry");

    foreach (XmlNode video in videos)
    {
        XmlNode insideauthor = video.SelectSingleNode("author");

        string videoId = video.SelectSingleNode("id").InnerText.Replace("http://gdata.youtube.com/feeds/api/videos/", String.Empty);
        string author = insideauthor.SelectSingleNode("name").InnerText;

        // Trying to get the views of a video of the search results
        MessageBox.Show(video.SelectSingleNode("yt:statistics").Attributes["viewCount"].InnerText);
    }

乔瑞。

【问题讨论】:

  • 你应该学会正确地使用命名空间,而不是使用 hacky 字符串替换来避免它们。如果此提要的操作员决定开始在其entry 元素上使用命名空间前缀,那么您的应用程序将无缘无故地中断。

标签: c# attributes xmldocument colon selectsinglenode


【解决方案1】:
XmlNodeList videos = doc.GetElementsByTagName("entry");

foreach (XmlNode video in videos)
{
    string videoId = video["id"].InnerText.Replace("http://gdata.youtube.com/feeds/api/videos/", String.Empty);
    string author = video["author"]["name"].InnerText;
    string views = video["yt:statistics"].Attributes["viewCount"].Value;

    Console.WriteLine(videoId);
    Console.WriteLine(author);
    Console.WriteLine(views);
}

【讨论】:

  • 谢谢,没想到这么简单!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 2013-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多