[英]Multiple XML Namespaces in tag with LXML
我正在嘗試使用Pythons 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"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.