使用Python编辑xml文件中的值 [英] Editing values in a xml file with Python
问题描述
嘿。我想在Python Web应用程序中有一个用于设置的config.xml文件。
Hey. I want to have a config.xml file for settings in a Python web app.
我手动制作了 car.xml 。看起来像这样:
I made car.xml manually. It looks like this:
<car>
<lights>
<blinkers>off</blinkers>
</lights>
</car>
现在,我想使用 xml.etree来查看信号灯是打开还是关闭。 ElementTree 。
import xml.etree.ElementTree as ET
tree = ET.parse('car.xml')
blinkers = tree.findtext('lights/blinkers')
print blinkers
> off
现在我想打开和关闭闪光灯,该怎么办?
Now I want to turn the blinkers on and off, how can I do this?
推荐答案
XML是存储配置设置的一种较差的方法。首先,在设置环境中XML并非完全对人类友好。特别是在Python世界中,最好使用设置模块(如@AaronMcSmooth所述)。不幸的是,Java世界中的许多项目都(错误地)使用XML进行设置,从而使其成为一种趋势。我认为这种趋势确实很糟糕。使用本机设置(Python中的模块)或更人性化的工具(例如YAML)。
XML is a rather poor way of storing configuration settings. For one, XML is not exactly human friendly in the context of settings. In the Python universe in particular you are better off using a settings module (as @AaronMcSmooth commented). Unfortunately a lot of projects in the Java world have (mis?)used XML for settings thereby making it a trend. I'd argue that this trend really sucks. Use native settings (module in Python) or something more human friendly like YAML.
这篇关于使用Python编辑xml文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!