views:

51

answers:

4

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"&gt;
  <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.

A: 

oWriter.WriteStartElement("Placemark"); should work, because the parent node already has the right namespace.

Hinek
@Hinek - That was how I had the code initially and it gives the empty xmlns. I've changed my code to reflect this, putting the namespace in the write of placemark actually will not allow the elements to be written.
Stevo3000
A: 

Did you try:

oWriter.WriteStartElement("kml", "Placemark", "kml");
onof
@onof - I take it u meant kml not klm; edited on this assumption. This still does not work.
Stevo3000
A: 

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.

Stevo3000
It may be valid, but it's bad practice.
Jason
@Jason - Unless you can offer a 'good' way to do this then this is not 'bad' practice; it is the only way to achieve this!
Stevo3000
+1  A: 

You needed

oWriter.WriteStartElement("Placemark", "http://www.opengis.net/kml/2.2");

otherwise the Placemark element gets put in the null namespace, which is why the xmlns="" attribute is added when you serialize the XML.

Alohci
This does not work, as I've already stated.
Stevo3000
You mean you do this, and it still serializes with xmlns="" on the Placemark element? Or something else?
Alohci
@Alohci - Even if you do that you still get xmlns="" on the Placemark element.
Stevo3000