ilya1725 ilya1725 - 1 year ago 46
Python Question

Saving XML files using ElementTree

I'm trying to develop simple Python (3.2) code to read XML files, do some corrections and store them back. However, during the storage step ElementTree adds this namespace nomenclature. For example:

<ns0:name>ACTIVE LOG</ns0:name>
<ns0:trkpt lat="38.5" lon="-120.2">
<ns0:trkpt lat="40.7" lon="-120.95">
<ns0:trkpt lat="43.252" lon="-126.453">

The code snippet is below:

def parse_gpx_data(gpxdata, tzname=None, npoints=None, filter_window=None,
ET = load_xml_library();

def find_trksegs_or_route(etree, ns):
if trksegs:
return trksegs, "trkpt"
else: # try to display route if track is missing
return rte, "rtept"

# try GPX10 namespace first
element = ET.XML(gpxdata)
except ET.ParseError as v:
row, column = v.position
print ("error on row %d, column %d:%d" % row, column, v)

print ("%s" % ET.tostring(element))
trksegs,pttag=find_trksegs_or_route(element, GPX10)
if not trksegs: # try GPX11 namespace otherwise
trksegs,pttag=find_trksegs_or_route(element, GPX11)
if not trksegs: # try without any namespace
trksegs,pttag=find_trksegs_or_route(element, "")

# Store the results if requested
if output_file_name:
ET.register_namespace('', GPX11)
ET.register_namespace('', GPX10)
ET.ElementTree(element).write(output_file_name, xml_declaration=True)


I have tried using the
, but with no positive result.
Are there any specific changes for this version of ElementTree 1.3?

Answer Source

In order to avoid the ns0 prefix the default namespace should be set before reading the XML data.

ET.register_namespace('', "")
ET.register_namespace('', "")