简体   繁体   中英

How to remove unnecessary xmlns attribute in C#?

I'm trying to update an existing XML file, but always when I update it adding new tags the xmlns="" attribute mysteriously appears in all tags and I didn't find a way to remove it.

    private static void EditarXML(string path, List<SiteUrl> listaUrls, bool indice, string loc)
    {
        XmlDocument documentoXML = new XmlDocument();
        documentoXML.Load(path);

            XmlNode sitemap = documentoXML.CreateElement("sitemap");

            XmlNode xloc = documentoXML.CreateElement("loc");
            xloc.InnerText = loc;
            sitemap.AppendChild(xloc);

            XmlNode lastmod = documentoXML.CreateElement("lastmod");
            lastmod.InnerText = DateTime.Now.ToShortDateString();
            sitemap.AppendChild(lastmod);

            documentoXML.DocumentElement.AppendChild(sitemap);
    }

Any help or ideas would be appreciated.

This will happen with the parent node you are appending to has a namespace, but you don't specify it in the CreateElement() call.

To handle this, you can get the namespace from the DocumentElement , like this (my sample just creates the document in memory, but the principle is the same), and pass it to CreateElement() .

  if (x.DocumentElement != null) {
    var xmlns = (x.DocumentElement.NamespaceURI);
    var sitemap = x.CreateElement("sitemap", xmlns);

    var xloc = x.CreateElement("loc", xmlns);
    xloc.InnerText = "Hello";
    sitemap.AppendChild(xloc);

    var lastmod = x.CreateElement("lastmod", xmlns);
    lastmod.InnerText = DateTime.Now.ToShortDateString();
    sitemap.AppendChild(lastmod);

    x.DocumentElement.AppendChild(sitemap);
  }
  Console.WriteLine(x.InnerXml);

Output

<test xmlns="jdphenix"><sitemap><loc>Hello</loc><lastmod>4/20/2015</lastmod></sitemap></test>

Note that if I did not pass the parent namespace to each CreateElement() call, the children of that call would have the blank xmlns .

  // incorrect - appends xmlns=""
  if (x.DocumentElement != null) {
    var sitemap = x.CreateElement("sitemap");

    var xloc = x.CreateElement("loc");
    xloc.InnerText = "Hello";
    sitemap.AppendChild(xloc);

    var lastmod = x.CreateElement("lastmod"); 
    lastmod.InnerText = DateTime.Now.ToShortDateString();
    sitemap.AppendChild(lastmod);

    x.DocumentElement.AppendChild(sitemap);
  }
  Console.WriteLine(x.InnerXml);

Output

<test xmlns="jdphenix"><sitemap xmlns=""><loc>Hello</loc><lastmod>4/20/2015</lastmod></sitemap></test>

Related reading: Why does .NET XML append an xlmns attribute to XmlElements I add to a document? Can I stop it?

How to prevent blank xmlns attributes in output from .NET's XmlDocument?

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