简体   繁体   中英

Python ElementTree

Having trouble with XML config files using ElementTree. I want to have an easy way to find the text of an element regardless of where it is in the XML Tree. From what the documentation says, I should be able to do this with findtext(), but no matter what, I get a return of None. Where am I going wrong here? Everyone was telling me XML is so simple to handle in Python, yet I have had nothing but troubles.

configFileName = 'file.xml'

def configSet (x):
if os.path.exists(configFileName):
    tree = ET.parse(configFileName)
    root = tree.getroot()
    return root.findtext(x)

hiTemp = configSet('hiTemp')
print hiTemp

and the XML

<configData>
<units>
    <temp>F</temp>
</units>
<pins>
    <lights>1</lights>
    <fan>2</fan>
    <co2>3</co2>
</pins>
<events>
    <airTemps>
        <hiTemp>80</hiTemp>
        <lowTemp>72</lowTemp>
        <hiTempAlarm>84</hiTempAlarm>
    </airTemps>
    <CO2>
        <co2Hi>1500</co2Hi>
        <co2Low>1400</co2Low>
        <co2Alarm>600</co2Alarm>
    </CO2>
</events>
<settings>
    <apikeys>
        <prowl>
            <apikey>None</apikey>
        </prowl>
    </apikeys>
</settings>

expected result

80

actual result

None

You can use xpath to get to your desired element.

return root.find('./events/airTemps/hiTemp').text

There's easy to follow documentation here .

findtext requires a full path, but you have given a relative path, so you cannot find the element you are looking for.

You can either provide a good xpath or modify your code

def configSet(x):
    if os.path.exists(configFileName):
        tree = ET.parse(configFileName)
        root = tree.getroot()
        for e in root.getiterator():
           t = e.findtext(x)
           if t is not None:
               return t

Update 1:

If you want to have all matched text as a list, the code is a bit different.

def configSet(x):
    matches = []
    if os.path.exists(configFileName):
        tree = ET.parse(configFileName)
        root = tree.getroot()
        for e in root.getiterator():
           t = e.findtext(x)
           if t is not None:
               matches.append(t)
    return matches

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM