为了在python中轻松操作XML,我喜欢
Beautiful Soup库.它的工作原理如下:
示例XML文件:
leaf1
leaf2
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()
#
#
# leaf1
#
#
# leaf2
#
#
# leaf3
#
#