Editing values in a xml file with Python

主宰稳场 提交于 2019-12-01 14:45:18

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.

You can remove nodes by calling the parent node's remove method, and insert nodes by calling ET.SubElement:

import xml.etree.ElementTree as ET

def flip_lights(tree):
    lights = tree.find('lights')
    state=get_blinker(tree)
    blinkers = tree.find('lights/blinkers')
    lights.remove(blinkers)
    new_blinkers = ET.SubElement(lights, "blinkers")
    new_blinkers.text='on' if state=='off' else 'off'

def get_blinker(tree):
    blinkers = tree.find('lights/blinkers')
    return blinkers.text

tree = ET.parse('car.xml')
print(get_blinker(tree))
# off
flip_lights(tree)
print(get_blinker(tree))
# on
flip_lights(tree)
print(get_blinker(tree))
# off
flip_lights(tree)
print(get_blinker(tree))
# on
tree.write('car2.xml')

Without addressing the merits of using XML instead of a Python module for managing configuration files, here's how to do what you asked using lxml:

>>> from lxml import etree
>>> xml = """<car>
   <lights>
      <blinkers>on</blinkers>
   </lights>
</car>"""
>>> doc = etree.fromstring(xml)
>>> elm = doc.xpath("/car/lights/blinkers")[0]
>>> elm.text="off"
>>> etree.tostring(doc)
'<car>\n   <lights>\n      <blinkers>off</blinkers>\n   </lights>\n</car>'

Take a look at this article.

But consider AaronMcSmooth's comment above -- this may be the wrong approach to your overall problem.

Use beautifulstonesoup. Here is the section on modifying xml:

http://www.crummy.com/software/BeautifulSoup/documentation.html#Modifying%20the%20Parse%20Tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!