Python ElementTree Basic Read operations Example _python

Source: Internet
Author: User
Examples can be downloaded in the attachment
1. Load XML file
There are 2 ways to load an XML file, one is to load the specified string, and the other is to load the specified file
2. Method of acquiring element
A) through Getiterator
b) Over GetChildren
C) Find method
D) FindAll method
Examples are as follows:
Copy Code code as follows:

#-*-Coding:utf-8-*-
From Xml.etree import ElementTree
def print_node (node):
"' Print the basic information of the node '".
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 the XML file '
# Load XML file (2 methods, one is to load the specified string, the other is to load the specified file)
# root = Elementtree.parse (r "D:\test.xml")
Root = elementtree.fromstring (text)

# methods to get the element
# 1 through Getiterator
Lst_node = Root.getiterator ("person")
For node in Lst_node:
Print_node (node)

# 2 through 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 ())

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.