Generating XML

We'll cover the following...

Python’s support for XML is not limited to parsing existing documents. You can also create XML documents from scratch.

Press + to interact
import xml.etree.ElementTree as etree
new_feed = etree.Element('{http://www.w3.org/2005/Atom}feed', #①
attrib={'{http://www.w3.org/XML/1998/namespace}lang': 'en'}) #②
print(etree.tostring(new_feed)) #③
#<ns0:feed xmlns:ns0='http://www.w3.org/2005/Atom' xml:lang='en'/>

① To create a new element, instantiate the Element class. You pass the element name (namespace + local name) as the first argument. This statement creates a feed element in the Atom namespace. This will be our new document’s root element.

② To add attributes to the newly created element, pass a dictionary of attribute names and values in the attrib argument. Note that the attribute name should be in the standard ElementTree format, {namespace}localname.

③ At any time, you can serialize any element (and its children) with the ElementTree tostring() function.

Was that serialization surprising to you? The way ElementTree serializes namespaced XML elements is technically accurate but not optimal. The sample xml document at the beginning of this chapter ...