Learning Python Network Programming

(Sean Pound) #1
Chapter 3

These are not the easiest lines of code at first glance, so let's break them down.
The minidom library can't directly work with ElementTree elements, so we use
ElementTree's tostring() function to create a string representation of our XML.
We load the string into the minidom API by using minidom.parseString(),
and then we use the toprettyxml() method to output our formatted XML.


This can be wrapped into a function so that it becomes more handy. Enter the
command block as shown in the following into your Python shell:





def xml_pprint(element):





... s = ET.tostring(element)


... print(minidom.parseString(s).toprettyxml())


Now, just do the following to pretty print:





xml_pprint(root)





<?xml version="1.0" ?>




Element attributes

In the example shown at the beginning of this section, you may have spotted
something in the opening tag of the element, that is, the id="c01" text.
This is called an attribute. We can use attributes to attach extra information to
elements, and there's no limit to the number of attributes an element can have.
Attributes are always comprised of an attribute name, which in this case is id,
and a value, which in this case is c01. The values can be any text, but they must
be enclosed in quotes.


Now, add the id attribute to the element, as shown here:





cheese.attrib['id'] = 'c01'








xml_pprint(cheese)





<?xml version="1.0" ?>



Caerphilly

The attrib attribute of an element is a dict-like object which holds an element's
attribute names and values. We can manipulate the XML attributes as we would a
regular dict.

Free download pdf