SoFunction
Updated on 2025-03-10

How to use Python modules to parse and manipulate XML data

Date: 2025.01.04 17:30:45 author: lijianzhan

Brief description: It is part of the Python standard library and is a module in the Python standard library for parsing and manipulating XML data, so it does not need to be installed through pip install. As long as you have Python installed (whether it is Python or Python), you can use it directly. It provides a simple and efficient way to process XML files, supporting parsing, creating, modifying, and querying XML data.

Introduce modules

import  as ET
print(ET.__version__)  # Print version information

Detailed introduction, ElementTree basic concept: Element: represents a node in XML, including tags, attributes (attribs) and child nodes (children). ElementTree: represents the tree structure of the entire XML document.
After knowing the basic concept, you can use internal methods to parse XML. The code example is as follows:

#Parase XML

1. Parsing from file

import  as ET
# parse XML filestree = ('')
root = ()  # Get the root element

2. Parsing from strings

xml_data = '''
<root>
    <child >Text1</child>
    <child >Text2</child>
</root>
'''
root = (xml_data)  # Parsing from string

3 Obtain XML format data and traverse the node code as follows:

xml_content =  # Get response dataroot = (xml_content)# parse XML# traverse all game elementsfor game in ('game'):

4. Completely obtain XML data from the requested http interface, and parse the step example of the data. The code is as follows:

import time
import requests
from time import sleep
import  as ET
class GetM061Com:
    def getLogin(self, username, password):
        print("Login module")
        url = '?mode=login'
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'
        }
        data = {
            'mode': 'login',
            'username': username,
            'password': password,
        }
        res = (url, headers=headers, data=data)
        if res.status_code == 200:
            xml_content =  # Get response data            root = (xml_content) # parse XML data            return ('uid').text
    def getIndex(self, uid):
        print("Home Module")
        if not uid:
            print("No valid uid was obtained")
            return
        # Get the current second-level time stamp        current_time_s = ()
        # Convert a second-level timestamp to a millisecond-level timestamp        current_time_ms = int(current_time_s * 1000)
        sleep(3)
        url = '?mode=index'
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'
        }
        data = {
            'uid': uid,
            'mode': 'home',
            'ts': current_time_ms
        }
        res = (url, headers=headers, data=data)
        if res.status_code == 200:
            xml_content =  # Get response data            root = (xml_content)# parse XML            # traverse all game elements            for game in ('game'):
                game_id = ('id')
                gtype = ('gtype').text
                if gtype == 'football':
                    print("-football")
                    print("game_id:" + game_id)
                elif gtype == 'basketball':
                    print("-basketball")
                    print("game_id:" + game_id)
if __name__ == '__main__':
    username = ''# account    password = ''# password    uid = GetM061Com().getLogin(username, password)
    GetM061Com().getIndex(uid)

5. Summary

It is a powerful tool for processing XML data, suitable for parsing, modifying, and generating XML files. Its interface is simple and easy to use and can meet most XML processing needs. If you have more complex needs (such as namespace processing), consider using the lxml library, which provides more powerful features and better performance.

This is the article about using Python module parsing and manipulating XML data. For more related Python parsing XML content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!