XML 和 Python:获取在根元素中声明的命名空间 [英] XML and Python: Get the namespaces declared in root element

查看:32
本文介绍了XML 和 Python:获取在根元素中声明的命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问 XML 树根元素处的多个 xmlns 声明?例如:

How do I access the multiple xmlns declarations at the root element of an XML tree? For example:

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 和匹配的标签

I want to get a dictionary similar to this one, or at least some format to make it easier to get the URI and the matching tag

{'one':"http://www.first.uri/here/", 'two':"http://www.second.uri/here/"}

推荐答案

我不确定如何使用 xml.etree 完成此操作,但是使用 lxml.etree 你可以这样做:

I'm not sure how this might be done with xml.etree, but with lxml.etree you could do this:

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

这篇关于XML 和 Python:获取在根元素中声明的命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆