解析在 XML 中具有命名空间的根节点的属性

Parse attributes of root node having namespace in 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"])