在使用ElementTree的XML配置文件时遇到问题。我想要一个简单的方法来查找元素的文本,而不管它在XML树中的位置。从文档中所说的话,我应该可以用findtext()来做到这一点,但无论如何,我都会返回None。我在哪里错了?大家都在告诉我,XML在Python中处理起来非常简单,但我除了麻烦之外什么都没有。Python ElementTree
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
和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>
预期的结果
80
实际结果
None
这可能是'os.path.exists(configFileName)'返回'False'。添加'else:raise IOError(“File not found。”)'看看是否是这种情况。 – jonrsharpe
它正在找到该文件,因为我可以返回根目录并且它给了我父母的元素。 – jslay