gpt4 book ai didi

python - LXML 标签中的多个 XML 命名空间

转载 作者:太空狗 更新时间:2023-10-29 17:18:44 26 4
gpt4 key购买 nike

我正在尝试使用 Python 的 LXML 库创建一个 Garmin 的 Mapsource 产品可以读取的 GPX 文件。他们的 GPX 文件的标题看起来像这样

<?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 不喜欢它。

知道如何让它没有 ns0 标签吗?

最佳答案

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

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

将 schemaLocation 放入 xsi 命名空间。

我想你的意思是

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

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

结果为

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

关于python - LXML 标签中的多个 XML 命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2850823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com