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

3

如何访问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个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接