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=""
M_Griffiths
  • 547
  • 1
  • 7
  • 26
  • Google is your friend: https://stackoverflow.com/questions/135000/how-to-prevent-blank-xmlns-attributes-in-output-from-nets-xmldocument – Thomas K Oct 05 '18 at 09:20

1 Answers1

0

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;
har07
  • 88,338
  • 12
  • 84
  • 137