On Mar 27, 2010, at 6:02 PM, Tyler Erickson wrote:

I have been trying to use the ElementTree library to generate KML
documents.  This seems to be straightforward for elements that are in
the default KML namespace, but I'm unsure of how to include elements
from other namespaces (such as atom:name).

The following is an example that (hopefully) illustrates the issues.
My questions are listed after the example.

#============================================
import xml.etree.cElementTree as ET
atom_ns = 'http://www.w3.org/2005/Atom'

# create a simple atom:name element
name_element = ET.Element(ET.QName(atom_ns, 'name'))
name_element.text = 'John Smith'

print 'ET.tostring(name_element, encoding="UTF-8")='
print ET.tostring(name_element, encoding="UTF-8")
print

# wrap the atom:name element in a KML element
kml_element = ET.Element("kml")
kml_element.set('xmlns','http://www.opengis.net/kml/2.2')
kml_element.set('xmlns:atom','http://www.w3.org/2005/Atom')
kml_element.append(name_element)

print 'ET.tostring(kml_element, encoding="UTF-8")='
print ET.tostring(kml_element, encoding="UTF-8")
print
#===========================================

When run, this test script produces the following:

$ python namespace_test.py

ET.tostring(name_element, encoding="UTF-8")=
<?xml version='1.0' encoding='UTF-8'?>
<ns0:name xmlns:ns0="http://www.w3.org/2005/Atom";>John Smith</
ns0:name>

ET.tostring(kml_element, encoding="UTF-8")=
<?xml version='1.0' encoding='UTF-8'?>
<kml xmlns="http://www.opengis.net/kml/2.2"; xmlns:atom="http://
www.w3.org/2005/Atom">
   <ns0:name xmlns:ns0="http://www.w3.org/2005/Atom";>John Smith</
ns0:name>
</kml>

Related to this example, here are my questions...

1. Is there a way to control what namespace prefix is used (I would
rather use 'atom' than 'ns0' in the above example)?  This would be
advantageous for writing tests that try to reproduce examples in the
OGC KML spec.

2. Is there a way to propagate the xmlns namespace definitions up to
the highest level element? Currently the atom namespace is defined in
both the kml and atom:name elements, and the atom:name definition
seems unnecessary.

ElementTree emits namespaces liberally. I don't think there's any way around it short of writing your own serializer. There's a namespaces map in the module that you can modify if you want to use particular prefixes (see the source or docs), but as Fredrik always points out it shouldn't make any difference to a standards-compliant XML parser.

Myself, I've returned to XML templates, after I determined that it's not really that much slower in my cases. ZPT or Jinja2 or string.Template instead of the ElementTree (or lxml) writer.

--
Sean

To unsubscribe from this group, send email to python-gis-sig+unsubscribegooglegroups.com 
or reply to this email with the words "REMOVE ME" as the subject.

Reply via email to