1

I am having a little issue. when i uise the following code to add to my xml file there is an empty xmlns="" beinmg added to it. How do i stop that from happening?

XmlDocument doc = new XmlDocument();        
    doc.Load(HttpContext.Current.Server.MapPath(@"~/Sitemap.xml"));
    XmlElement root = doc.DocumentElement;
    XmlElement ele = doc.CreateElement("url");      
    ele.Attributes.RemoveNamedItem("xmlns");
    XmlElement locele = doc.CreateElement("loc");
    locele.InnerText = urlstring;
    XmlElement lastmodele = doc.CreateElement("lastmod");
    lastmodele.InnerText = DateTime.Now.ToString();
    XmlElement chgfrqele = doc.CreateElement("changefreq");
    chgfrqele.InnerText = "weekly";
    ele.AppendChild(locele);
    ele.AppendChild(lastmodele);
    ele.AppendChild(chgfrqele);
    root.AppendChild(ele);
    doc.Save(HttpContext.Current.Server.MapPath(@"~/Sitemap.xml"));

My outputted xml should look like this:

    <?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>www.url.com/test</loc>
    <lastmod>03/10/2018 10:01:43</lastmod>
    <changefreq>weekly</changefreq>
  </url> 
  <url>
    <loc>www.url.com/test</loc>
    <lastmod>05/10/2018 09:31:12</lastmod>
    <changefreq>weekly</changefreq>
  </url>


</urlset>

Unfortunately, it ends up looking like this:

<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
     <url xmlns="">
    <loc>www.url.com/test</loc>
    <lastmod>05/10/2018 09:15:40</lastmod>
    <changefreq>weekly</changefreq>
  </url>
  <url xmlns="">
    <loc>www.url.com/test</loc>
    <lastmod>05/10/2018 09:21:40</lastmod>
    <changefreq>weekly</changefreq>
  </url>
</urlset>

How do I stop it adding the following to my URL element?:

xmlns=""
1

1 Answer 1

1

xmlns without prefix is known as default element. Notice that descendant element without prefix inherit default namespace from ancestor implicitly. When you create element without specifying any namespace it will be created in empty namespace instead of in the default namespace, hence the xmlns="". So to avoid that you need to specify the namespace on creating new element, for example:

XmlElement locele = doc.CreateElement("loc", "http://www.sitemaps.org/schemas/sitemap/0.9");
locele.InnerText = urlstring;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.