C# issues with generating sitemap.xml dynamically

Hello,

I want to generate sitemap.xml dynamically and having trouble reading the existing sitemap.xml and updating it. First step (code show bellow) is to clear the sitemap.xml file node urlset.

when code is executed, I'm getting the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
selectedNode.RemoveAll();

One thing I noticed is if I clear urlset attributes it will work fine
<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">
obviously, the problem is that it will not become a valid sitemap..

appreciate your help
string configPath = Server.MapPath("~/sitemap.xml");
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(configPath);
 
        XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
        XmlNode selectedNode = xmlDoc.SelectSingleNode("//urlset", nsMgr);
 
 
 
        selectedNode.RemoveAll();
        XmlElement nodeElmt = xmlDoc.CreateElement("urlset");
 
        xmlDoc.Save(Server.MapPath(configPath));

Open in new window

NevinsLtdAsked:
Who is Participating?
 
oobaylyCommented:
The XmlNamespaceManager doesn't cope well with default namespaces, ie those without a prefix. Try the following:
nsMgr.AddNamespace("default", "http://www.sitemaps.org/schemas/sitemap/0.9");
XmlNode selectedNode = xmlDoc.SelectSingleNode("//default:urlset", nsMgr);

Open in new window

0
 
NevinsLtdAuthor Commented:
thank you for your quick response..
that solved the first challange but created another challenge which is producing the follownig tag:
 <url xmlns="">

which should be  <url>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.