[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 470
  • Last Modified:

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

0
NevinsLtd
Asked:
NevinsLtd
1 Solution
 
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

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now