问题描述
我试图从python中的模板xml文件生成自定义的xml文件。
I'm trying to generate customized xml files from a template xml file in python.
从概念上说,我想在模板xml中读取,删除一些元素,更改一些文本属性,并将新的xml输出到一个文件。我想要这样做:
Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:
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()
now I want to write to file, but I don't see how to get toElementTree.ElementTree.write()
conf_new.write('config-new.xml')
有没有办法还是有人建议以不同的方式做这个事情?
Is there some way to do this, or can someone suggest doing this a different way?
推荐答案
为了在python中轻松处理XML,我喜欢库。它的工作原理如下:
For easy manipulation of XML in python, I like the Beautiful Soup library. It works something like this:
示例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'
可以使用节点名称作为方法:
You can use the node names as methods:
soup.root.contents[0].name
# u'level1'
还可以使用正则表达式:
It is also possible to use regexes:
import re
tags_starting_with_level = soup.findAll(re.compile('^level'))
for tag in tags_starting_with_level: print tag.name
# level1
# level2
添加和插入新节点非常简单:
Adding and inserting new nodes is pretty straightforward:
# 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>
这篇关于在python中编辑XML作为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!