Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple XML Namespaces in tag with LXML

Tags:

python

xml

lxml

gpx

I am trying to use Pythons LXML library to create 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">

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?

like image 305
lonerockz Avatar asked May 17 '10 16:05

lonerockz


1 Answers

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. It puts the attribute in the http://www.w3.org/2001/XMLSchema-instance namespace

That gives the 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"/>
like image 102
mmmmmm Avatar answered Oct 13 '22 01:10

mmmmmm