2

I'm processing XML files with ElementTree that have about 5000 of these "asset" nodes per file

<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>

I need
the value of the id attribute on the asset node
the text of the vin node
the text of the gps node

How can I read the text of the 'vin' and 'gps' child nodes directly without having to iterate over all of the child nodes?

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))
Michael Geiser
  • 365
  • 1
  • 14

1 Answers1

2

You can execute XPath relative to each asset element to get vin and gps directly without looping :

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))
har07
  • 88,338
  • 12
  • 84
  • 137
  • I'm a little torqued that PyCharm isn't auto-completing ET for me...and (in hindsight) https://docs.python.org/2/library/xml.etree.elementtree.html is clearer now...much appreciated! – Michael Geiser Feb 21 '19 at 14:09