element1 daily

Select Linq nodes in Xml C #

XML file format:

<?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> 

I want to select all the "loc" nodes (element1, element2), but this does not work !!!

  foreach (XElement item in document.Elements("url").Descendants("loc")) // Change into what? { urlList.Add(item.Value); } 
+6
source share
3 answers

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); } } 
+12
source
 var xDoc = XDocument.Parse( @"<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>"); var locElements = xDoc.Descendants("url").SelectMany(el => el.Descendants("loc")); 
+3
source

Try the following:

 var query = for x in xDoc.Descendants("url") select (string)x.Element("loc"); foreach (string loc in query) { urlList.Add(loc); } 
+1
source

Source: https://habr.com/ru/post/894434/


All Articles