XML和Python:获取在根元素中声明的名称空间

时间:2010-08-07 01:28:37

标签: python xml xml-namespaces

如何在XML树的根元素处访问多个xmlns声明?例如:

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

我希望得到一个与此类似的字典,或者至少是某种格式,以便更容易获取URI和匹配标记

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

1 个答案:

答案 0 :(得分:2)

我不确定如何使用xml.etree完成此操作,但使用lxml.etree可以执行此操作:

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