python - 在 Python 中获取根节点的属性(命名空间)
问题描述
我需要提取 xml 文件开头的名称空间。
它看起来像这样。
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:a="CannotGetThisAttrib" xmlns:b="CannotGetThisAttrib">
<fileHeader c="CanGetThisAttrib/>>
<body></body>
<fooder/>
</root>
我可以提取根节点下的属性。但是,我无法获取根节点属性 a 和 b,它们是解析 xml 文件所必需的命名空间。
tree = ET.parse("xmlfile.xml")
root = tree.getroot()
root.attrib => None
root[0].attrib["c"] => CanGetThisAttrib
任何建议表示赞赏。
解决方案
这里(使用 lxml)
from lxml import etree
data = '''<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:a="CannotGetThisAttrib" xmlns:b="CannotGetThisAttrib">
<fileHeader c="CanGetThisAttrib"/>
<body></body>
<fooder/>
</root>
'''
data = data.encode('ascii')
tree = etree.fromstring(data)
for k,v in tree.nsmap.items():
print('{} -> {}'.format(k,v))
输出
a -> CannotGetThisAttrib
b -> CannotGetThisAttrib
推荐阅读
- c# - 如果 Enum.GetValues(typeof()) 的枚举值在 Model 中声明,为什么无法识别它们?
- r - 将csv数据导入R进行文本挖掘时出错
- ios - 将联系人直接保存到 iOS 中的 sim 卡中
- sql - Sqlalchemy 使用 json_set 更新特定的 JSON 字段
- javascript - 通过许多请求在 javascript 中使用相同的 http 会话
- reactjs - 在 react-table 中显示布尔值和时间戳值:React Table+ React+Typescript
- dynamic - 如何在动态查询中包含'?
- php - 如何使用php删除字符串中的重复字符?
- python - 如何将一个图像矩阵插入另一个图像矩阵?
- azure - 看不到 Azure SQL 的长期备份文件