在python中将XML编辑为字典?
我正在尝试从python中的模板xml文件生成自定义xml文件。
从概念上讲,我想读入xml模板,删除一些元素,更改一些文本属性,然后将新的xml写到文件中。我希望它能像这样工作:
conf_base = ConvertXmlToDict('config-template.xml')
conf_base_dict = conf_base.UnWrap()
del conf_base_dict['root-name']['level1-name']['leaf1']
del conf_base_dict['root-name']['level1-name']['leaf2']
conf_new = ConvertDictToXml(conf_base_dict)
现在我想写文件,但是我看不到如何进入ElementTree.ElementTree.write()
conf_new.write('config-new.xml')
有什么办法可以做到这一点,还是有人可以建议以其他方式做到这一点?
-
为了方便地在python中处理XML,我喜欢Beautiful
Soup库。它的工作原理如下:示例XML文件:
<root> <level1>leaf1</level1> <level2>leaf2</level2> </root>
Python代码:
from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString soup = BeautifulStoneSoup('config-template.xml') # get the parser for the xml file soup.contents[0].name # u'root'
您可以将节点名称用作方法:
soup.root.contents[0].name # u'level1'
也可以使用正则表达式:
import re tags_starting_with_level = soup.findAll(re.compile('^level')) for tag in tags_starting_with_level: print tag.name # level1 # level2
添加和插入新节点非常简单:
# build and insert a new level with a new leaf level3 = Tag(soup, 'level3') level3.insert(0, NavigableString('leaf3') soup.root.insert(2, level3) print soup.prettify() # <root> # <level1> # leaf1 # </level1> # <level2> # leaf2 # </level2> # <level3> # leaf3 # </level3> # </root>