I suspect the problem is that you are switching from document.Elements("url") instead of document.Root.Elements("url") ... so it searches for the root element of a url that does not exist.
Try the following:
List<string> urlList = doc.Root.Elements("url") .Elements("loc") .Select(x => (string) x) .ToList();
Note that I did not use Descendants here, since loc elements are still under url elements.
Another alternative that you could use if in any case the only loc elements are correct is simple:
List<string> urlList = doc.Descendants("loc") .Select(x => (string) x) .ToList();
(I assume urlList was empty beforehand ... for this kind of situation, I like to use LINQ for the whole operation and exclude foreach loops that are just added to the collection.)
EDIT: The code works for me. Here's a short but complete program:
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; class Test { static void Main(string[] args) { string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <urlset> <url> <loc>element1</loc> <changefreq>daily</changefreq> <priority>0.2</priority> </url> <url> <loc>element2</loc> <changefreq>daily</changefreq> <priority>0.2</priority> </url> </urlset>"; XDocument doc = XDocument.Parse(xml); List<string> urlList = doc.Root .Elements("url") .Elements("loc") .Select(x => (string) x) .ToList(); Console.WriteLine(urlList.Count); } }
source share