LXML标签中的多个XML命名空间 [英] Multiple XML Namespaces in tag with LXML

查看:250
本文介绍了LXML标签中的多个XML命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Pythons的LXML库来创建GPX文件,Garmin的Mapsource产品可以读取该文件.他们的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">

当我使用以下代码时:

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))

我得到:

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

具有烦人的ns0标记.这可能是完全有效的XML,但Mapsource不满意.

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

任何想法如何使它不具有ns0标记?

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

推荐答案

问题出在您的属性名称上.

The problem is with your attribute name.

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

将schemaLocation放入xsi命名空间中.

puts schemaLocation in the xsi namespace.

我想你是说

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

使用xsi的URL.这与您在元素名称中使用名称空间变量相匹配.它将属性放在http://www.w3.org/2001/XMLSchema-instance命名空间

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

得出的结果

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

这篇关于LXML标签中的多个XML命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆