Multiple XML Namespaces in tag with LXML

帅比萌擦擦* 提交于 2019-12-04 16:41:05

问题


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?


回答1:


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"/>


来源:https://stackoverflow.com/questions/2850823/multiple-xml-namespaces-in-tag-with-lxml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!