Develop with libvrt python API, xml parse and operation is frequently required. ElementTree (stantard python library) is introduced in python-xml-parse come into used for the sake of simplify xml configuration lifecycle handling.
This blog will go throught xml.etree.ElementTree combine with typical situations which is use as learning notes.
First, start with some basic concepts
The Element type is a flexible container object, designed to store hierarchical data structures in memory. The type can be described as a cross between a list and a dictionary.
Each element has a number of properties associated with it:
a tag which is a string identifying what kind of data this element represents (the element type, in other words).
a number of attributes, stored in a Python dictionary.
a text string.
an optional tail string.
a number of child elements, stored in a Python sequence
Python 2.7.5 (default, Aug 4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import xml.etree.ElementTree as ET >>> tree = ET.parse('test_data.xml') >>> root = tree.getroot() >>> root <Element 'data' at 0x7f58bd8232d0>
>>> for country in root.findall('country'): ... rank = country.find('rank').text ... name = country.get('name') ... print name, rank ... Liechtenstein 1 Singapore 4 Panama 68
use find all, all tag with name country is found and its rank text and attribute name is listed.
change the parameters for test, change findall target, test if tag not matched what will happend:
1 2 3
>>> for country in root.findall('test'): ... print country ...
when use find instead of findall
1 2 3 4 5 6 7 8
>>> for tag in root.find('country'): ... print tag ... <Element 'rank' at 0x7f58bd823f90> <Element 'year' at 0x7f58bd823fd0> <Element 'gdppc' at 0x7f58bd825050> <Element 'neighbor' at 0x7f58bd825090> <Element 'neighbor' at 0x7f58bd8250d0>
only first matched result is returned.
if find for a unexists tag None will be returned.
1 2
>>> print root.find('test') None
so in most cases, find and findall seems meet all the require for finding a specific tag.