I\'m trying to generate customized xml files from a template xml file in python.
Conceptually, I want to read in the template xml, remove some elements, change some
For easy manipulation of XML in python, I like the Beautiful Soup library. It works something like this:
Sample XML File:
leaf1
leaf2
Python code:
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()
#
#
# leaf1
#
#
# leaf2
#
#
# leaf3
#
#