Last active
August 29, 2015 14:09
-
-
Save brain-zhang/3b2a6688598afdf90685 to your computer and use it in GitHub Desktop.
simple parse xml file(utf-8) with comment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/env python | |
| # -*- coding: utf-8 -*- | |
| import xml.etree.ElementTree as ET | |
| class CommentedTreeBuilder(ET.XMLTreeBuilder): | |
| def __init__(self, html = 0, target = None): | |
| ET.XMLTreeBuilder.__init__(self, html, target) | |
| self._parser.CommentHandler = self.handle_comment | |
| def handle_comment(self, data): | |
| self._target.start(ET.Comment, {}) | |
| self._target.data( data ) | |
| self._target.end(ET.Comment) | |
| def genconfig(xml_path, tag, text): | |
| """ set tag's text, "<tag>text</tag>" """ | |
| xml_config_tree = ET.parse(xml_path, parser=CommentedTreeBuilder()) | |
| for elem in xml_config_tree.iter(tag=tag): | |
| elem.text = text | |
| xml_config_tree.write(xml_path, xml_declaration=True, encoding='utf-8') | |
| def genconfig_attr(xml_path, tag, attr, value): | |
| """ set attr's value of tag, "<tag attr=value></tag>" """ | |
| xml_config_tree = ET.parse(xml_path, parser=CommentedTreeBuilder()) | |
| for elem in xml_config_tree.iter(tag=tag): | |
| elem.attrib[attr] = value | |
| xml_config_tree.write(xml_path, xml_declaration=True, encoding='utf-8') |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
简单的parse一个xml文件,提供修改tag和attr的两个方法。默认UTF-8格式parse,支持注释