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 “loc” nodes (element1, element2), but this not work!!!
foreach (XElement item in document.Elements("url").Descendants("loc")) // Change into what?
{
urlList.Add(item.Value);
}
I suspect the problem is that you’re going from
document.Elements("url")instead ofdocument.Root.Elements("url")… so it’s looking for a root element ofurl, which doesn’t exist.Try this:
Note that I haven’t used
Descendantshere, as thelocelements are all directly beneathurlelements anyway.Another alternative you could use if the only
locelements are the right ones anyway, is just:(I’m assuming
urlListwas empty beforehand… for this sort of situation I like to use LINQ for the whole operation and eliminateforeachloops that are just adding to a collection.)EDIT: The code works for me. Here’s a short but complete program: