problem
You want to read an XML document, make the most changes to it, and then write the results back to the XML document.
Solution Solutions
These tasks can be easily handled using the Xml.etree.ElementTree module. The first step is to parse the document in the usual way. For example, suppose you have a document named Pred.xml, similar to the following:
Here is an example of using ElementTree to read this document and make some changes to it:
>>> from Xml.etree.ElementTree Import Parse, element>>> doc = Parse (' Pred.xml ') >>> root = Doc. Getroot () >>> root
>>> # Remove a few elements>>> root.remove (Root.find (' Sri ') ) >>> Root.remove (root.find (' CR ')) >>> # Insert A new element after
...
>>> Root.getchildren (). Index (Root.find (' nm ')) 1>>> e = Element (' spam ') >>> E.text = ' This is a Test ' >>> Root.insert (2, E) >>> # Write back to a file>>> doc.write (' Newpred.xml ', Xml_ declaration=true) >>>
The processing result is a new XML file such as the following:
Discuss
It's easy to modify an XML document structure, but you have to keep in mind that all of the modifications are for the parent node element, which is treated as a list. For example, if you delete an element, it is removed from its immediate parent node by calling the Remove () method of the parent node. If you insert or add a new element, you also use the Insert () and Append () methods of the parent node element. You can also use index and slice operations on elements, such as element[i] or element[i:j]
If you need to create a new element, you can use the element class shown in the scenario in this section. We have discussed it in detail in section 6.5.