This section briefly introduces how to parse and modify XML documents using Python.

Source: Internet
Author: User

This section briefly introduces how to parse and modify XML documents using Python.

Problem
You want to read an XML document, modify it the most, and write the result back to the XML document.


Solution

The xml. etree. ElementTree module can easily process these tasks. The first step is to parse this document in the usual way. For example, suppose you have a document named pred. xml, which is similar to the following:

Here is an example of using ElementTree to read this document and make some modifications to it:

>>> from xml.etree.ElementTree import parse, Element>>> doc = parse('pred.xml')>>> root = doc.getroot()>>> root<Element 'stop' at 0x100770cb0>>>> # Remove a few elements>>> root.remove(root.find('sri'))>>> root.remove(root.find('cr'))>>> # Insert a new element after <nm>...</nm>>>> 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 like the following:


Discussion
It is easy to modify the structure of an XML document, but you must remember that all modifications are made to the parent node element and processed as a list. For example, if you delete an element, you can call the remove () method of the parent node to delete it from its direct parent node. If you insert or add new elements, you also use the insert () and append () Methods of the parent node elements. You can also use indexes and slices for elements, such as element [I] or element [I: j].

If you need to create new elements, you can use the Element class demonstrated in this section. We have discussed it in detail in section 6.5.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.