tags:

views:

192

answers:

1

I am trying to use Pythons LXML library to great a GPX file that can be read by Garmin's Mapsource Product. The header on their GPX files looks like this

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" 
creator="MapSource 6.15.5" version="1.1" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"&gt;

When I use the following code:

xmlns="http://www.topografix.com/GPX/1/1"
xsi="http://www.w3.org/2001/XMLSchema-instance"
schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
version="1.1"
ns = "{xsi}"
getXML = etree.Element("{"+xmlns+"}gpx",version=version, attrib={"{xsi}schemaLocation" : schemaLocation}, creator='My Product', nsmap={'xsi':xsi, None:xmlns})
print(etree.tostring(getXML, xml_declaration=True, standalone='Yes', encoding="UTF-8", pretty_print=True))

I get:

<?xml version=\'1.0\' encoding=\'UTF-8\' standalone=\'yes\'?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/1" xmlns:ns0="xsi"
ns0:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd"
version="1.1" creator="My Product"/>

Which has the annoying 'ns0' tag. This might be perfectly valid XML but Mapsource does not appreciate it.

Any idea how to get this to not have the ns0 tag?

A: 

The problem is with your attribute name.

attrib={"{xsi}schemaLocation" : schemaLocation},

puts schemaLocation in the xsi namespace I think you meant

attrib={"{" + xsi + "}schemaLocation" : schemaLocation}

to use the URL for xsi. This matches your uses of namespace variables in the element name.

That gives teh result of

<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<gpx xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1     http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" creator="My Product"/>
Mark
See this is why I am an amateur and don't code for a living! Perfect answer. Thanks!
lonerockz