python - 使用命名空间和属性获取值
问题描述
具有以下格式的文件(我尽可能地缩小了数据,因为它是一个非常大的文件)。这是 RAW 格式的未来 274 小时的天气预报:
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<kml:kml xmlns:dwd="https://opendata.dwd.de/weather/lib/pointforecast_dwd_extension_V1_0.xsd" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<kml:Document>
<kml:ExtendedData>
<dwd:ProductDefinition>
... #Several more Values
<dwd:ForecastTimeSteps>
<dwd:TimeStep>2021-07-22T10:00:00.000Z</dwd:TimeStep>
... #247 Values
</dwd:ForecastTimeSteps>
</dwd:ProductDefinition>
</kml:ExtendedData>
<kml:Placemark>
<kml:name>K2932</kml:name>
<kml:description>TUTTLINGEN</kml:description>
<kml:ExtendedData>
<dwd:Forecast dwd:elementName="PPPP">
<dwd:value>###247 PPPP-Values according to the Time above###.</dwd:value>
</dwd:Forecast>
<dwd:Forecast dwd:elementName="E_PPP">
<dwd:value>###247 E_PP-Values according to the Time above###</dwd:value>
</dwd:Forecast>
... ### Many more of there Elements
<dwd:Forecast dwd:elementName="RR1c">
<dwd:value>###247 RR1c-Values according to the Time above###</dwd:value>
</dwd:Forecast>
</kml:ExtendedData>
</kml:Placemark>
</kml:Document>
</kml:kml>
我需要获取 RR1C 的值。这是我的方法:
from xml.etree import ElementTree as etree
dwd = '{https://opendata.dwd.de/weather/lib/pointforecast_dwd_extension_V1_0.xsd}'
with open('./tmp/forecast/MOSMIX_L_2021072209_K2932.kml', 'rt') as f:
root = etree.parse(f)
root.find('.//{0}Forecast'.format(dwd)).attrib['{0}elementName'.format(dwd)]
出 []: 'PPPP'
我不知道如何深入到“RR1c”以及“价值观”本身。任何人?
解决方案
正如 Michael Kay 在评论中指出的那样,这可以在 XPath 的帮助下完成。这是一个例子:
from xml.etree import ElementTree as etree
# declare namespaces map
ns = {
'dwd' : 'https://opendata.dwd.de/weather/lib/pointforecast_dwd_extension_V1_0.xsd'
}
with open('./tmp/forecast/MOSMIX_L_2021072209_K2932.kml', 'rt') as f:
root = etree.parse(f)
# retrieve value using xpath (returns list of elements matching criteria)
forecasts = root.findall('.//dwd:Forecast[@dwd:elementName="RR1c"]/dwd:value', ns)
# print text of the first element found
print(forecasts[0].text)
推荐阅读
- c# - 当类不使用 JSON 字符串提供的所有属性时,将 JSON 字符串转换为类
- java - 列表接口的 add 方法在没有正文时如何工作?list接口的add方法定义在哪里?
- laravel-5 - Laravel Lumen 5.4 中的迁移引发“遇到非数值”错误
- linux - Git 的平均备份时间是多少
- asp.net-mvc - ASP.NET MVC 使用编辑器模板创建对象
- google-cloud-platform - 谷歌物联网与 Xively api 可用性
- c# - 使用 MongoDB 和 C# 新驱动程序版本 (2.0) 更新嵌入式文档属性
- html - 如果使用输入组,使用 Bootstrap4 表单是否需要标签
- vba - VBA Shape.Fill.UserPicture 不加载图片
- typescript - 在 Flow 中导入 TypeScript 模块