这个粗略的代码使用了一个非常有用的库,叫做BeautifulSoup。它用作 HTML/XML 标记语言的解析器,提供 python 对象模型。它可用于从 XML 中提取/更改信息或通过构建对象模型来创建 XML。
下面的代码通过从 pastebin 上的模板更改 XML 标记来工作。它通过复制模板“item”标签、清除其子标签并用可能来自数据库的合适字典条目来填充它们来做到这一点。
# 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)