XML and Python: Get the namespaces declared in root element

妖精的绣舞 提交于 2019-12-22 09:59:44

问题


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/">

          ...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:


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/">

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


来源:https://stackoverflow.com/questions/3428792/xml-and-python-get-the-namespaces-declared-in-root-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!