gpt4 book ai didi

python - XML 和 Python : Get the namespaces declared in root element

转载 作者:数据小太阳 更新时间:2023-10-29 02:37:52 26 4
gpt4 key购买 nike

如何访问 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com