I am trying to traverse through a simple sitemap (adding and deleting elements on the fly.) This is the sample layout
<?xml version='1.0' encoding='UTF-8'?> <urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd'> <url> <loc>http://mysite.com/</loc> <priority>1.00</priority> <changefreq>daily</changefreq> </url> <url> <loc>http://mysite.com/Default.aspx</loc> <priority>0.80</priority> <changefreq>daily</changefreq> </url> </urlset>
Weirdly when I try to access a child element using the Element() method after loading the document, it’s null, and so is Elements(), so I can’t traverse through them. The Nodes() method has the elements though.
Here’s the code I wrote
XElement siteMap = XElement.Load(Server.MapPath('~/sitemap.xml')); //First remove all article nodes foreach (XElement elem in siteMap.Elements()) { XElement loc = elem.Element('loc'); if (loc.Value.Contains('http://mysite.com/articles/')) elem.Remove(); }
No matter what I do to try and retrieve the elements of elem (Element, Elements), I get a null.
What could be wrong? This code is supposed to run. Isn’t it?
You could also do the following instead: