XML and Python: get namespaces declared in root element

How to access multiple declarations xmlnsin the root element of an XML tree? For instance:

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

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

{'one':"http://www.first.uri/here/", 'two':"http://www.second.uri/here/"}
+3
source share
1 answer

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

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/'}
+2
source

Source: https://habr.com/ru/post/1757463/


All Articles