Question

I've parsed some of the XML that youtube API returns. The XML I'm trying to parse can be found on a URL like this http://gdata.youtube.com/feeds/api/videos?v=2&q=stackoverflow

The nodes I'm trying to get are yt:accessControl and I'm not sure how to do this. I've tried with SelectNodes but got an empty result.

Was it helpful?

Solution

For youtube, I think you don't need that - google has API wrapper specifically for .NET: https://developers.google.com/youtube/2.0/developers_guide_dotnet

But if you still wish to do it manually, LINQ to XML methods like Descendants and Element take an XName as an argument. There is a conversion from string to XName that is happening automatically for you. You can fix this by adding an XNamespace before the strings in your Descendants and Element calls. Watch out because you have 2 different namespaces at work.

XNamespace ns = "http://gdata.youtube.com/schemas/2007";
var xElements = XElement.Parse(File.ReadAllText(@"c:\test\youtube.xml"))
                        .Descendants(ns + "accessControl");

Without Linq it would look something like this:

var xdoc = new XmlDocument();
xdoc.Load(@"c:\test\youtube.xml");
var namespaceManager = new XmlNamespaceManager(xdoc.NameTable);
namespaceManager.AddNamespace("yt", "http://gdata.youtube.com/schemas/2007");
var xmlNodeList = xdoc.SelectNodes("//yt:accessControl", namespaceManager);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top