简体   繁体   中英

prevent empty xmlns attribute being created

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=""

Try this:

private static void RemoveEmptyNamespace(XElement element)
{
    XAttribute attr = element.Attribute("xmlns");
    if (attr != null && string.IsNullOrEmpty(attr.Value))
        attr.Remove();
    foreach (XElement el in element.Elements())
        RemoveEmptyNamespace(el);
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM