This rough code uses a very useful library called BeautifulSoup. It serves as a parser for HTML/XML markup languages providing a python object model. It can be used to extract/change information from XML or create XML by building up the object model.
This code below works by changing XML tags from a the template on pastebin. It does this by copying the template "item" tag, clearing its child tags and filling them with the suitable dictionary entries which will be presumably sourced from a database.
# Import System libraries
from copy import copy
from copy import deepcopy
# Import Custom libraries
from BeautifulSoup import BeautifulSoup, BeautifulStoneSoup, Tag, NavigableString, CData
def gen_xml(record):
description_blank_str = \
'''
<item>
<title>Entry Title</title>
<link>Link to the entry</link>
<guid>http://example.com/item/123</guid>
<pubDate>Sat, 9 Jan 2010 16:23:41 GMT</pubDate>
<description>[CDATA[ This is the description. ]]</description>
</item>
'''
description_xml_tag = BeautifulStoneSoup(description_blank_str)
key_pair_locations = \
[
("title", lambda x: x.name == u"title"),
("link", lambda x: x.name == u"link"),
("guid", lambda x: x.name == u"guid"),
("pubDate", lambda x: x.name == u"pubdate"),
("description", lambda x: x.name == u"description")
]
tmp_description_tag_handle = deepcopy(description_xml_tag)
for (key, location) in key_pair_locations:
search_list = tmp_description_tag_handle.findAll(location)
if(not search_list):
continue
tag_handle = search_list[0]
tag_handle.clear()
if(key == "description"):
tag_handle.insert(0, CData(record[key]))
else:
tag_handle.insert(0, record[key])
return tmp_description_tag_handle
test_dict = \
{
"title" : "TEST",
"link" : "TEST",
"guid" : "TEST",
"pubDate" : "TEST",
"description" : "TEST"
}
print gen_xml(test_dict)