Not all elements of the XML input will end up as elements of the parsed tree. Currently, this module skips over any XML comments, processing instructions, and document type declarations in the input. Nevertheless, trees built using this module’s API rather than parsing from XML text can have comments and processing instructions in them; they will be included when generating XML output.
Create and Build XML Documents
Import Element Tree module
Element() function is used to create XML elements
SubElement() function used to create sub-elements to a give element
dump() function is used to dump xml elements.
If you want to save to a file create a xml tree with ElementTree() function and to save to a file use write() method
Comment() function is used to insert comments in xml file.
Modifying an XML File
Import Element Tree module and open xml file, get an xml element
Element object can be manipulated by changing its fields, adding and modifying attributes, adding and removing children
If you want to remove an element use Element.remove() method
ElementTree.write() method used to output xml object to xml files.
Opening and reading large XML files using iterparse (incremental parsing)
Sometimes we don't want to load the entire XML file in order to get the information we need. In these instances, being able to incrementally load the relevant sections and then delete them when we are finished is useful. With the iterparse function you can edit the element tree that is stored while parsing the XML.
Import the ElementTree object:
Open the .xml file and iterate over all the elements:
Alternatively, we can only look for specific events, such as start/end tags or namespaces. If this option is omitted (as above), only "end" events are returned:
Here is the complete example showing how to clear elements from the in-memory tree when we are finished with them:
Opening and reading using an ElementTree
Import the ElementTree object, open the relevant .xml file and get the root tag:
There are a few ways to search through the tree. First is by iteration:
Otherwise you can reference specific locations like a list:
To search for specific tags by name, use the
Searching the XML with XPath
Starting with version 2.7
ElementTree has a better support for XPath queries. XPath is a syntax to enable you to navigate through an xml like SQL is used to search through a database. Both
findall functions support XPath. The xml below will be used for this example
Searching for all books:
Searching for the book with title = 'The Colour of Magic':
Searching for the book with id = 5:
Search for the second book:
Search for the last book:
Search for all authors: