如何访问 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/"}
最佳答案
我不确定如何使用 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/'}
关于python - XML 和 Python : Get the namespaces declared in root element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3428792/