Python elementtree Basic Read Operation example

Source: Internet
Author: User
Examples can be downloaded in attachments
1. Loading an XML file
There are 2 ways to load an XML file, one to load the specified string, and two to load the specified file
2. How to obtain the element
A) through Getiterator
b) Over GetChildren
C) Find method
D) FindAll method
Examples are as follows:
Copy CodeThe code is as follows:


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

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

# 2 via 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.