0

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.

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
user2246242
  • 101
  • 1
  • 12

1 Answers1

0

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?

Community
  • 1
  • 1
jdphenix
  • 15,022
  • 3
  • 41
  • 74