使用Python xml.etree.ElementTree获取XBRL根节点属性返回空字典
问题:ElementTree获取XBRL根节点命名空间属性返回空字典
尝试使用Python的xml.etree.ElementTree模块读取一份意大利XBRL格式的资产负债表文件,获取根节点属性时得到空字典。
文件开头内容
<?xml version="1.0" encoding="UTF-8"?> <xbrl xmlns="http://www.xbrl.org/2003/instance" xmlns:itcc-ci-ese="http://www.infocamere.it/itnn/fr/itcc/ci/ese/2018-11-04" xmlns:link="http://www.xbrl.org/2003/linkbase" xmlns:itcc-ci="http://www.infocamere.it/itnn/fr/itcc/ci/2018-11-04" xmlns:iso4217="http://www.xbrl.org/2003/iso4217" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xbrli="http://www.xbrl.org/2003/instance"> ... </xbrl>
测试代码
import xml.etree.ElementTree as ET tree = ET.parse('...\\000001108.XBRL') root = tree.getroot() print(root.attrib)
实际输出
{}
预期输出
{'xmlns': 'http://www.xbrl.org/2003/instance', 'xmlns:itcc-ci-ese': 'http://www.infocamere.it/itnn/fr/itcc/ci/ese/2018-11-04', 'xmlns:link': 'http://www.xbrl.org/2003/linkbase', 'xmlns:itcc-ci': 'http://www.infocamere.it/itnn/fr/itcc/ci/2018-11-04', 'xmlns:iso4217': 'http://www.xbrl.org/2003/iso4217', 'xmlns:xlink': 'http://www.w3.org/1999/xlink', 'xmlns:xbrli': 'http://www.xbrl.org/2003/instance'}
解决方案
ElementTree会将xmlns开头的命名空间声明视为特殊属性,不会放入attrib字典中,而是单独管理。可以通过以下两种方式获取这些命名空间:
方法1:使用nsmap属性(Python 3.8及以上版本)
Python 3.8开始,ElementTree的节点对象新增了nsmap属性,直接返回命名空间映射字典:
import xml.etree.ElementTree as ET tree = ET.parse('...\\000001108.XBRL') root = tree.getroot() print(root.nsmap)
输出示例:
{'': 'http://www.xbrl.org/2003/instance', 'itcc-ci-ese': 'http://www.infocamere.it/itnn/fr/itcc/ci/ese/2018-11-04', 'link': 'http://www.xbrl.org/2003/linkbase', 'itcc-ci': 'http://www.infocamere.it/itnn/fr/itcc/ci/2018-11-04', 'iso4217': 'http://www.xbrl.org/2003/iso4217', 'xlink': 'http://www.w3.org/1999/xlink', 'xbrli': 'http://www.xbrl.org/2003/instance'}
注:默认命名空间(无前缀的xmlns)对应的键是空字符串。
方法2:手动筛选命名空间属性(兼容低版本Python)
如果使用Python 3.8以下版本,可以通过遍历节点的items()方法,筛选出所有以xmlns开头的属性:
import xml.etree.ElementTree as ET tree = ET.parse('...\\000001108.XBRL') root = tree.getroot() ns_attributes = {k: v for k, v in root.items() if k.startswith('xmlns')} print(ns_attributes)
此方法会直接返回你预期格式的字典,包含完整的xmlns开头属性键名。
内容的提问来源于stack exchange,提问作者Francesco
相关产品推荐
相关产品推荐

