Search code examples
c#.netxmlxmlwriter

XmlWriter writing empty xmlns


I'm using the following code to initialise an XmlDocument

XmlDocument moDocument = new XmlDocument();
moDocument.AppendChild(moDocument.CreateXmlDeclaration("1.0", "UTF-8", null));
moDocument.AppendChild(moDocument.CreateElement("kml", "http://www.opengis.net/kml/2.2"));

Later in the process I write some values to it using the following code

using (XmlWriter oWriter = oDocument.DocumentElement.CreateNavigator().AppendChild())
{
  oWriter.WriteStartElement("Placemark");
  //....
  oWriter.WriteEndElement();
  oWriter.Flush();
}

This ends up giving me the following xml when I save the document

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Placemark xmlns="">
    <!-- -->   
  </Placemark>
</kml>

How can I get rid of the empty xmlns on the Placemark element?

--EDITED TO SHOW CHANGE TO HOW PLACEMARK WAS BEING WRITTEN--
If I put the namespace in the write of placemark then non of the elements are added to the document.


Solution

  • I have fixed the issue by creating the document with the following code (no namespace in the document element)

    XmlDocument moDocument = new XmlDocument(); 
    moDocument.AppendChild(moDocument.CreateXmlDeclaration("1.0", "UTF-8", null)); 
    moDocument.AppendChild(moDocument.CreateElement("kml"));
    

    And by saving it with the following code to set the namespace before the save

    moDocument.DocumentElement.SetAttribute("xmlns", msNamespace);
    moDocument.Save(msFilePath);
    

    This is valid as the namespce is only required in the saved xml file.