SoFunction
Updated on 2024-11-18

Introduction to Python gods are this way to deal with XML files

Recently, some students asked how to use Python to deal with xml files, hereby compiling a more concise operation manual for your reference.

First prepare an xml file with the following contents in the xml. Store as:

To get the data inside this xml, we need to utilize ElementTree in Python.

The specific operations are shown below:

1, import the package (package is built-in Python comes with)

2. Open the file and get the attributes of the root node and the node name

After running the code, the result is shown below:

3, the use of find method to obtain child nodes (disadvantage: only according to the name provided to obtain the first child node)

The results of the run are shown below:

4, the use of findall method to get all the child nodes, the return of the node will exist in a list of

The results of the run are shown below: The results of the run are shown below:

5, the use of findall method to obtain all three levels of child nodes, the return of the node will exist inside a list

The results of the run are shown below:

6、Use the traversal method to directly traverse all the elements inside the child nodes

The results of the run are shown below:

This is the end of our xml processing!

I'll leave you with a practice problem: There is an xml file. The contents are as follows, saved as:

For the above xml file, the requirements are as follows:

◆ Write an XmlUtil class.

Write a function inside: get_page

Pass a parameter file_path

Implemented to read elements, return data in the form of a list, and store information about each page node inside the list.

◆ Write a page class

There are 2 attributes: page_key_word.

Stores page information; uiElement stores list data.

◆ Write a UiElement class

There is 1 attribute: stores list type data, treating each message as a piece of data inside the list.

This is the whole content of this article.