views:

42

answers:

1

How do I access the multiple xmlns declarations at the root element of an XML tree? For example:

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

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

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

I want to get a dictionary similar to this one, or at least some format to make it easier to get the URI and the matching tag

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

I'm not sure how this might be done with xml.etree, but with lxml.etree you could do this:

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

          ...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/'}
unutbu