XML Namespaces multiples dans la balise avec LXML
Question
Je suis en train d'utiliser la bibliothèque Pythons LXML pour créer un fichier GPX qui peut être lu par Mapsource Garmin produit. L'en-tête sur leurs fichiers GPX ressemble à ceci
<?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">
Quand j'utilise le code suivant:
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))
J'obtenir:
<?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"/>
Ce qui a l'étiquette de ns0
ennuyeux. Cela pourrait être XML parfaitement valide, mais Mapsource ne l'apprécient pas.
Toute idée comment obtenir ce pour ne pas avoir la balise ns0
?
La solution
Le problème est avec votre nom d'attribut.
attrib={"{xsi}schemaLocation" : schemaLocation},
met schemaLocation dans l'espace de noms xsi.
Je pense que vous vouliez dire
attrib={"{" + xsi + "}schemaLocation" : schemaLocation}
pour utiliser l'URL pour xsi. Cela correspond à vos utilisations des variables d'espace de noms dans le nom de l'élément. Il met l'attribut dans l'espace de noms http://www.w3.org/2001/XMLSchema-instance
Cela donne le résultat de
<?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"/>