阿小信大人的头像
做你说过的,说你能做的 阿小信大人

xml.etree.ElementTree的增删改查2014-09-02 05:10

xml:

<widgets>
    <groups><group>name1</group><group>name2</group><group>name3</group></groups>
    </widgets>

代码:

# -*- coding: utf-8 -*-

from xml.etree import ElementTree

def get_groups():
    result = []
    widgets = ElementTree.parse("./config.xml")# fromstring(text)
    groups = widgets.getiterator("group")
    for group in groups:
        result.append(group.text)
    return result

def add_group(group_name):
    group = ElementTree.Element("group")
    group.text = group_name
    widgets = ElementTree.parse("./config.xml")
    groups = widgets.find("groups")
    groups.append(group)
    widgets.write("./config.xml", encoding="utf-8")

def change_group_name(old_name, new_name):
    widgets = ElementTree.parse("./config.xml")
    groups = widgets.getiterator("group")
    for group in groups:
        if group.text == old_name:
            group.text = new_name
    widgets.write("./config.xml", encoding="utf-8")

def delete_group(name):
    widgets = ElementTree.parse("./config.xml")
    groups = widgets.getiterator("group")
    groups_node = widgets.find("groups")
    for group in groups:
        if group.text == name:
            groups_node.remove(group)
    widgets.write("./config.xml", encoding="utf-8")

change_group_name("name2", "change_group_name")

解析微信xml

def parse_xml(xml):
    from xml.etree import ElementTree
    return dict((child.tag, child.text)
                for child in ElementTree.fromstring(xml))

然而,最好用的xml解析工具是xmltodict,try it.

如果您觉得从我的分享中得到了帮助,并且希望我的博客持续发展下去,请点击支付宝捐赠,谢谢!

若非特别声明,文章均为阿小信的个人笔记,转载请注明出处。文章如有侵权内容,请联系我,我会及时删除。

#Python#  
分享到:
阅读[1057] 评论[0]

你可能也感兴趣的文章推荐

本文最近访客

发表评论