XML与Python:获取根元素中声明的命名空间
我该如何访问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/'}