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

标签 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/"}

最佳答案

我不确定如何使用 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/

相关文章:

javascript - 使用 jQuery 和 HTML 对 XML 数据进行分页

xml - 错误 : Undeclared namespace prefix x:

c# - 为什么 'xmlns' 属性会影响 XPath 节点查找?

python - 字符串连接 : Putting large chuck of text in Python code

python - Pandas 添加两个多索引数据帧

java - Gradle 失败 : unsupported node 'item' in ids. xml

Python XPath : Is it possible to have optional XPath query?

python - 我在哪里可以找到发布 GIL 的 numpy 函数列表?

python - 拆分列表中的元素并分隔字符串,然后计算长度

xml - XSL - 如何从源 xml 中删除未使用的 namespace ?