使用 Python 打印 xml 文件中的值 3

Print values from an xml file using Python 3

我正在尝试使用 ElementTree 从下面的 xml 文件打印值,但似乎无法实现所需的输出(如下所示)。

xml

<?xml version="1.0" encoding="UTF-8"?>
    <forecast>
        <area aac="QLD_PT002" description="Maroochydore" type="location" parent-aac="QLD_ME002">
            <forecast-period index="0" start-time-local="2021-08-03T05:00:00+10:00" end-time-local="2021-08-04T00:00:00+10:00" start-time-utc="2021-08-02T19:00:00Z" end-time-utc="2021-08-03T14:00:00Z">
                <element type="forecast_icon_code">17</element>
                <element type="precipitation_range">0 to 0.4 mm</element>
                <element type="air_temperature_maximum" units="Celsius">27</element>
                <text type="precis">Possible late shower.</text>
                <text type="probability_of_precipitation">40%</text>
            </forecast-period>
            <forecast-period index="1" start-time-local="2021-08-04T00:00:00+10:00" end-time-local="2021-08-05T00:00:00+10:00" start-time-utc="2021-08-03T14:00:00Z" end-time-utc="2021-08-04T14:00:00Z">
                <element type="forecast_icon_code">3</element>
                <element type="air_temperature_minimum" units="Celsius">11</element>
                <element type="air_temperature_maximum" units="Celsius">21</element>
                <text type="precis">Mostly sunny.</text>
                <text type="probability_of_precipitation">20%</text>
            </forecast-period>
            <forecast-period index="2" start-time-local="2021-08-05T00:00:00+10:00" end-time-local="2021-08-06T00:00:00+10:00" start-time-utc="2021-08-04T14:00:00Z" end-time-utc="2021-08-05T14:00:00Z">
                <element type="forecast_icon_code">1</element>
                <element type="air_temperature_minimum" units="Celsius">7</element>
                <element type="air_temperature_maximum" units="Celsius">21</element>
                <text type="precis">Sunny.</text>
                <text type="probability_of_precipitation">0%</text>
            </forecast-period>
        </area>
    </forecast>

脚本

import xml.etree.ElementTree as ElemTree
  
root = ElemTree.parse('C:\IDQ10611.xml').getroot()
for elem in root.findall(".//area"):
    print(elem.attrib['description'], ';', sep='', end='')
    fc = elem.findall("./forecast-period/element[@type = 'air_temperature_minimum']")
    print(fc)

输出

Maroochydore;[<Element 'element' at 0x000001A7743026D0>, <Element 'element' at 0x000001A774302CC0>]

需要输出

Maroochydore;[11, 7]

你快到了。尝试

for elem in root.findall(".//area"):
    print(elem.attrib['description'], ';', sep='', end='')
    fc = elem.findall('.//forecast-period/element[@type="air_temperature_minimum"][@units="Celsius"]')
    print([f.text for f in fc])

输出:

Maroochydore;['11', '7']