开发者

XML and Python: Get the namespaces declared in root element

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.s开发者_运维技巧econd.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/"}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜