29

I am trying to write out the following element using XmlWriter

<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">

I've got the very first declaration done using

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

How can I add the remaining 3 declarations to the same element?

Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53
etechpartner
  • 640
  • 1
  • 7
  • 12

3 Answers3

51
writer.WriteAttributeString("xmlns","gx", null, "http://www.google.com/kml/ext/2.2");
writer.WriteAttributeString("xmlns","kml", null, "http://www.opengis.net/kml/2.2");
writer.WriteAttributeString("xmlns","atom", null, "http://www.w3.org/2005/Atom");

Got that from https://msdn.microsoft.com/en-us/library/cfche0ka(v=vs.100).aspx.

shashwat
  • 7,851
  • 9
  • 57
  • 90
Ryan B
  • 848
  • 6
  • 9
9

The answer of Ryan B is incomplete as the XML namespace is only written as attribute but not registered in the name table, so LookupPrefix will fail getting prefix of one of the XML namespaces, f.i. http://www.w3.org/2005/Atom. It will return null instead atom.

To write a namespace attribute and get namespace registered use

writer.WriteAttributeString("atom",
                            "http://www.w3.org/2000/xmlns/",
                            "http://www.w3.org/2005/Atom");

Use of namespace http://www.w3.org/2000/xmlns/registers also the prefix in name table.

VBWebProfi
  • 309
  • 3
  • 4
  • It is worth noting the unstated bit here: including the URI for the xmlns namespace has the side-effect of writing "xmlns" to the attribute, thus the leading parameter seen in the earlier code is not needed. – Maury Markowitz Nov 11 '22 at 17:16
0

The namespaces are simply attributes. Use the standards means of writing attributes for the element.

Francis Upton IV
  • 19,322
  • 3
  • 53
  • 57