Python elementtree basic read operation example

Source: Internet
Author: User

The example can be downloaded from the attachment.
1. load XML files
There are two ways to load an XML file: loading a specified string and loading a specified file.
2. Obtain the Element Method
A) through getiterator
B) getchildren
C) Find Method
D) findall Method
Example: CopyCode The Code is as follows: #-*-coding: UTF-8 -*-
From XML. etree import elementtree
Def print_node (node ):
''''' Print basic node information '''
Print "============================================ ========"
Print "node. attrib: % s" % node. attrib
If node. attrib. has_key ("Age")> 0:
Print "node. attrib ['age']: % s" % node. attrib ['age']
Print "node. Tag: % s" % node. Tag
Print "node. Text: % s" % node. Text
Def read_xml (text ):
'''''' Read XML file '''
# Loading XML files (two methods: loading a specified string and loading a specified file)
# Root = elementtree. parse (R "D: \ test. xml ")
Root = elementtree. fromstring (text)

# Obtain the Element Method
#1 through getiterator
Lst_node = root. getiterator ("person ")
For node in lst_node:
Print_node (node)

#2 Use getchildren
Lst_node_child = lst_node [0]. getchildren () [0]
Print_node (lst_node_child)

#3. Find Method
Node_find = root. Find ('person ')
Print_node (node_find)

#4. findall Method
Node_findall = root. findall ("person/Name") [1]
Print_node (node_findall)

If _ name _ = '_ main __':
# Read_xml (open ("test. xml"). Read ())
Write_xml (open ("test. xml"). Read ())

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.