要实现按属性搜索和提取XML节点,可以使用Python中的xml.etree.ElementTree模块。下面是一个示例代码:
import xml.etree.ElementTree as ET
# 加载XML文件
tree = ET.parse('data.xml')
root = tree.getroot()
# 按属性搜索和提取节点
nodes = root.findall(".//book[@category='web']")
# 打印搜索结果
for node in nodes:
print(node.tag, node.attrib)
# 提取节点内容
for node in nodes:
title = node.find('title').text
author = node.find('author').text
price = node.find('price').text
print(f'Title: {title}')
print(f'Author: {author}')
print(f'Price: {price}')
print('---')
在上面的示例中,我们首先使用ET.parse()
函数加载XML文件,并使用getroot()
方法获取根节点。然后,我们使用findall()
方法和XPath表达式按属性搜索节点。这里的XPath表达式".//book[@category='web']"
表示查找所有名为"book"且具有属性"category"的节点,且属性值为"web"。
然后,我们可以遍历搜索结果,并使用tag
和attrib
属性获取节点的标签名和属性。我们还可以使用find()
方法和节点名称提取子节点的内容。
以上示例中的data.xml
文件内容如下:
Learning XML
Erik T. Ray
39.95
Python for Data Analysis
Wes McKinney
49.99
Head First Python
Paul Barry
29.99
运行以上代码将输出以下结果:
book {'category': 'web'}
book {'category': 'web'}
Title: Learning XML
Author: Erik T. Ray
Price: 39.95
---
Title: Python for Data Analysis
Author: Wes McKinney
Price: 49.99
---