Learning Python Network Programming

(Sean Pound) #1

APIs in Action


Let's add another element, and this time let's give it some content. Add the
following commands:





name = ET.SubElement(cheese, 'name')








name.text = 'Caerphilly'








ET.dump(root)





Caerphilly

Now, our document is starting to shape up. We do two new things here: first,
we use the shortcut class method ElementTree.SubElement() to create the
new element and insert it into the tree as a child of in a single
operation. Second, we give it some content by assigning some text to the element's
text attribute.


We can remove elements by using the remove() method on the parent element,
as shown in the following commands:





temp = ET.SubElement(root, 'temp')








ET.dump(root)





Caerphilly />



root.remove(temp)








ET.dump(root)





Caerphilly
Pretty printing

It would be useful for us to be able to produce output in a more legible format, such
as the example shown at the beginning of this section. The ElementTree API doesn't
have a function for doing this, but another XML API, minidom, provided by the
standard library, does, and it's simple to use. First, import minidom:





import xml.dom.minidom as minidom





Second, use the following command to print some nicely formatted XML:





print(minidom.parseString(ET.tostring(root)).toprettyxml())





<?xml version="1.0" ?>




Caerphilly

Free download pdf