python - 在 XML 中解析具有命名空间的根节点的属性
问题描述
我有以下 xml,我试图解析它并想要获取根节点的属性值,即xmlns:n1
值。但是我使用以下值得到了关键错误。
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<n1:Level-1C_Tile_ID xmlns:n1="https://psd-12.sentinel2.eo.esa.int/PSD/S2_PDI_Level-1C_Tile_Metadata.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://psd-12.sentinel2.eo.esa.int/PSD/S2_PDI_Level-1C_Tile_Metadata.xsd /dpc/app/s2ipf/FORMAT_METADATA_TILE_L1C/02.10.02/scripts/../../../schemas/02.12.05/PSD/S2_PDI_Level-1C_Tile_Metadata.xsd">
<n1:General_Info>
<TILE_ID metadataLevel="Brief">S2A_OPER_MSI_L1C_TL_MTI__20161111T091803_A007252_T43QBA_N02.04</TILE_ID>
<DATASTRIP_ID metadataLevel="Standard">S2A_OPER_MSI_L1C_DS_MTI__20161111T091803_S20161111T053350_N02.04</DATASTRIP_ID>
<DOWNLINK_PRIORITY metadataLevel="Standard">NOMINAL</DOWNLINK_PRIORITY>
<SENSING_TIME metadataLevel="Standard">2016-11-11T05:33:50.068Z</SENSING_TIME>
<Archiving_Info metadataLevel="Expertise">
<ARCHIVING_CENTRE>MTI_</ARCHIVING_CENTRE>
<ARCHIVING_TIME>2016-11-11T10:53:22.600451Z</ARCHIVING_TIME>
</Archiving_Info>
</n1:General_Info>
</n1:Level-1C_Tile_ID>
代码 :
from lxml import etree
tree = etree.parse(XML_FILE_CONTENT_PASTED_ABOVE)
root = tree.getroot()
print(root.attrib['xmlns:n1'])
错误 :
KeyError: 'xmlns:n1'
期望的输出:
https://psd-12.sentinel2.eo.esa.int/PSD/S2_PDI_Level-1C_Tile_Metadata.xsd
解决方案
命名空间声明 ( xmlns:n1='...'
) 看起来像一个属性,但它不是attrib
元素字典的一部分。
n1
要获取与前缀关联的命名空间 URI ,请使用nsmap
:
print(root.nsmap["n1"])
推荐阅读
- php - Laravel 嵌套查询多重关系
- laravel - 使用 belongsTo 的关系用户和子数据
- azure - 如何为 vNet 网关客户端使用 privateIPAllocationMethod
- jquery - 页面加载时如何显示 Bootstrap toast?
- angularjs - 在两个不同的控制器之间传输数据,它们都与不同的功能有关
- tomcat8 - 如何修复部署war文件后出现黑屏
- sql - 需要在python中传递一个带有单个\字符的字符串
- flutter - Provider 可以处理这样的复杂类的状态吗?如果没有,我怎样才能让这个类在全局状态下对我的整个应用程序可用?
- docker - Kubernetes 集群资源恢复
- r - 使用 sample () 在掷骰子中获得“单个”TRUE/FALSE 而不是多个