Scratchpad:Creating XML Using lxml.objectify

From OpenLP
Jump to: navigation, search

This page is outdated and needs to be updated

Caution: This code is written for Python 2. OpenLP now uses Python 3 which may render this sample invalid with out modification.

This snippet of code creates a sitemap according to the specs at sitemaps.org:

 1 E = objectify.ElementMaker(annotate=False,
 2     namespace=u'http://www.sitemaps.org/schemas/sitemap/0.9',
 3     nsmap={None: u'http://www.sitemaps.org/schemas/sitemap/0.9'})
 4 # Create the XML
 5 site_urls = [
 6     u'http://www.domain.com/home.html',
 7     u'http://www.domain.com/about.html',
 8     u'http://www.domain.com/contact.html',
 9 ]
10 urls = []
11 for url in site_urls:
12     urls.append(E.url(E.loc(url), E.changefreq(u'monthly'), E.priority(u'0.8')))
13 urlset = E.urlset(*urls)
14 pretty_xml = etree.tostring(urlset, encoding=u'utf8',
15     xml_declaration=u'<?xml version="1.0" encoding="UTF-8"?>', pretty_print=True)
16 sitemap_file = open(config.get(u'sitemap.filename', u'autos/public/sitemap.xml'), u'w+')
17 sitemap_file.write(pretty_xml)
18 sitemap_file.close()