Как прочитать текст определенных дочерних узлов в ElementTree?

Я обрабатываю XML-файлы с помощью ElementTree, у которых около 5000 таких узлов «актива» на файл.

<asset id="83">
    <name/>
    <tag>0</tag>
    <vin>3AKJGLBG6GSGZ6917</vin>
    <fleet>131283</fleet>
    <type id="0">Standard</type>
    <subtype/>
    <exsid/>
    <mileage>0</mileage>
    <location>B106</location>
    <mileoffset>0</mileoffset>
    <enginehouroffset>0</enginehouroffset>
    <radioaddress/>
    <mfg/>
    <inservice>04 Apr 2017</inservice>
    <inspdate/>
    <status>1</status>
    <opstatus timestamp="1491335031">unknown</opstatus>
    <gps>567T646576</gps>
    <homeloi/>
</asset>

Мне нужно
значение атрибута id на узле актива
текст узла vin
текст узла gps

Как я могу прочитать текст дочерних узлов «vin» и «gps» напрямую, не перебирая все дочерние узлы?

for asset_xml in root.findall("./assetlist/asset"):
    print(asset_xml.attrib['id'])
    for asset_xml_children in asset_xml:
        if (asset_xml_children.tag == 'vin'):
            print(str(asset_xml_children.text))
        if (asset_xml_children.tag == 'gps'):
            print(str(asset_xml_children.text))

person Michael Geiser    schedule 21.02.2019    source источник


Ответы (1)


Вы можете выполнить XPath относительно каждого элемента asset, чтобы получить vin и gps напрямую без цикла:

for asset_xml in root.findall("./assetlist/asset"):
    print(asset_xml.attrib['id'])

    vin = asset_xml.find("vin")
    print(str(vin.text))

    gps = asset_xml.find("gps")
    print(str(gps.text))
person har07    schedule 21.02.2019
comment
Я немного озадачен тем, что PyCharm не выполняет для меня автозаполнение ET... и (оглядываясь назад) docs.python.org/2/library/xml.etree.elementtree.html теперь понятнее... большое спасибо! - person Michael Geiser; 21.02.2019