Python uses ElementTree to operate XML to get the node reading attribute beautifying XML

Source: Internet
Author: User
Tags xml example
This article explains how to use ElementTree to parse XML, obtain son nodes, insert son nodes, operate attributes, and beautify XML.
Three classes, ElementTree, Element, and SubElement, which create subclass classes, are required.
From xml. etree. ElementTree import ElementTree
From xml. etree. ElementTree import Element
From xml. etree. ElementTree import SubElement as SE

2. read and parse
Tree = ElementTree (file = xmlfile)
Root = tree. getroot ()
After reading, the tree is of the ElementTree type. the getroot () method is used to obtain the xml root node;

XML example File:

The code is as follows:






3. get the son node
Find all child nodes of an Element:

The code is as follows:


Ry = item. findall ('A ')
You can also use getchildren ():
Childs = item. getchildren ()
For subItem in childs:
Print subItem. get ('id ')

4. Insert the son node
Method 1:

The code is as follows:


Item = Element ("item", {'Sid': '000000', 'name': 'ityouhui '})
Root. append (item)


Method 2:

The code is as follows:


SE (root, 'item', {'Sid': '000000', 'name': 'ityouhui '})


The advantage of Method 1 is that the item can be operated on after being inserted. Method 2 is simple in writing, SE is SubElement, and a statement is made at the introduction;

5. operation attributes
Get an attribute value of an Element (eg: get the name of an item)

The code is as follows:


Print root. find ('item/name'). text
Print item. get ('name ')


Get all attributes of Element

The code is as follows:


Print item. items () # [('Sid ', '123'), ('name', 'Big CC')]
Print item. attrib # {'Sid': '123456', 'name': 'Big CC '}

6. beautify XML
Before writing, input root to call this function. the written XML file format is neat and elegant:

The code is as follows:


Indent (root)
Book. write (xmlfile, 'utf-8 ')

The code is as follows:


# Get pretty look
Def indent (elem, level = 0 ):
I = "\ n" + level *""
If len (elem ):
If not elem. text or not elem. text. strip ():
Elem. text = I + ""
For e in elem:
Indent (e, level + 1)
If not e. tail or not e. tail. strip ():
E. tail = I
If level and (not elem. tail or not elem. tail. strip ()):
Elem. tail = I
Return elem

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.