views:

621

answers:

1

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"&gt;
  <url>
    <loc>http://mysite.com/&lt;/loc&gt;
    <priority>1.00</priority>
    <changefreq>daily</changefreq>
  </url>
  <url>
    <loc>http://mysite.com/Default.aspx&lt;/loc&gt;
    <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?

+3  A: 
var doc = XDocument.Load(Server.MapPath("~/sitemap.xml"));
foreach (XElement elem in doc.Root.Elements()) {
     var loc = elem.Element(XName.Get("loc","http://www.sitemaps.org/schemas/sitemap/0.9") );
     if (loc.Value.Contains("http://astrobix.com/articles/"))
         elem.Remove();
}

You could also do the following instead:

doc.Root.Elements()
   .Where(x => x.Element(XName.Get("loc", "http://www.sitemaps.org/schemas/sitemap/0.9"))
                .Value.Contains("http://astrobix.com/articles/"))
   .Remove();
Mehrdad Afshari
I am sorry Mehrdad, that didn't work. I am getting a NullReferenceException in the foreach line (siteMap.Element("urlset").Element("url"))Which is exactly the problem I am facing... Did this work with the said XML data at your end?
Cyril Gupta
This new one works. The problem is caused by the element name being defined in a namespace. If you specify the namespace explicitly, it'll work.
Mehrdad Afshari