溫馨提示×

Python怎么提取XML標(biāo)簽內(nèi)容

小億
271
2024-06-04 16:33:21
欄目: 編程語言

你可以使用Python的xml.etree.ElementTree模塊來提取XML標(biāo)簽內(nèi)容。以下是一個簡單的示例:

import xml.etree.ElementTree as ET

# 讀取XML文件
tree = ET.parse('example.xml')
root = tree.getroot()

# 提取所有標(biāo)簽為'item'的內(nèi)容
for item in root.findall('item'):
    # 提取標(biāo)簽為'title'的內(nèi)容
    title = item.find('title').text
    # 提取標(biāo)簽為'description'的內(nèi)容
    description = item.find('description').text
    
    print('Title:', title)
    print('Description:', description)

在這個示例中,我們首先使用ET.parse()函數(shù)讀取XML文件,然后使用findall()方法和find()方法來提取特定標(biāo)簽的內(nèi)容。在這個例子中,我們提取了所有標(biāo)簽為’item’的內(nèi)容,并分別提取了’title’和’description’標(biāo)簽的內(nèi)容。

0