2010-08-07 2 views
3

Comment accéder aux multiples déclarations xmlns à l'élément racine d'une arborescence XML? Par exemple:XML et Python: obtention des espaces de nom déclarés dans l'élément racine

import xml.etree.cElementTree as ET 
data = """<root 
      xmlns:one="http://www.first.uri/here/" 
      xmlns:two="http://www.second.uri/here/"> 

      ...all other child elements here... 
      </root>""" 

tree = ET.fromstring(data) 
# I don't know what to do here afterwards 

Je veux obtenir un dictionnaire semblable à celui-ci, ou au moins un format pour le rendre plus facile d'obtenir l'URI et la balise correspondant

{'one':"http://www.first.uri/here/", 'two':"http://www.second.uri/here/"} 

Répondre

2

Je ne suis pas sûr comment cela pourrait être fait avec xml.etree, mais avec lxml.etree vous pouvez le faire:

import lxml.etree as le 
data = """<root 
      xmlns:one="http://www.first.uri/here/" 
      xmlns:two="http://www.second.uri/here/"> 

      ...all other child elements here... 
      </root>""" 

tree = le.XML(data) 
print(tree.nsmap) 
# {'two': 'http://www.second.uri/here/', 'one': 'http://www.first.uri/here/'} 
Questions connexes