For e in etgetElementsByTag Nameexception

â– Note The following text might seem slightly confusing, because there is an overlap of terminology. XML elements can have attributes, as in this example: <element attribute="attribute value">element value</element>. Similarly, Python objects or classes also have attributes that you access like this: python_object.attribute. When XML is parsed and the representing Python object is built for your document, you would use Python class attributes to access XML document attributes.

Now I've reached the elements that I am interested in and need to extract their values. As you can see from the configuration file example, I chose to store data as element attributes. Attributes in each Element object can be accessed using an attribute called attributes. This attribute is an object that acts as a dictionary. Each element of the dictionary has two values: name contains name of the XML element attribute, and value holds the actual text value of the attribute.

It may sound confusing, but it should become clear if you look at the example in Listing 7-11.

Listing 7-11. Accessing configuration data in the XML document for et in config.getElementsByTagName('exception_types'): for e in et.getElementsByTagName('exception'): print e.attributes['logline'].value print e.attributes['headline'].value print e.attributes['body'].value print e.attributes['group'].value print e.attributes['desc'].value

As you can see from this example, searching for and accessing attributes of XML document elements is really a trivial task.

Was this article helpful?

0 0

Post a comment