# 遍历所有子元素
for child in root:
print(f"子元素: {child.tag}, 属性: {child.attrib}")
# 访问孙子元素
for subchild in child:
print(f" {subchild.tag}: {subchild.text}")
# 访问特定元素的文本
title = root.find('book/title') # 查找第一个匹配的元素
if title is not None:
print(f"书名: {title.text}")
# 查找所有符合条件的元素
all_books = root.findall('book') # 查找所有book元素
print(f"找到 {len(all_books)} 本书")
# 修改元素文本
for price in root.iter('price'): # iter()遍历所有price元素
old_price = float(price.text)
price.text = str(old_price * 0.9) # 打9折
price.set('discount', '10%') # 添加新属性
# 删除元素
for book in root.findall('book'):
year = book.find('year')
if year is not None and int(year.text) < 2010:
root.remove(book) # 删除2010年以前的书
# 保存修改
tree.write('updated_books.xml')
5. 查找元素的多种方式
python复制代码
# 1. 使用XPath-like语法(有限支持)
expensive_books = root.findall("book[price>50]") # 价格>50的书
# 2. 遍历所有特定标签
for author in root.iter('author'):
print(f"作者: {author.text}")
# 3. 复杂条件查找
for book in root.findall('book'):
price = float(book.find('price').text)
category = book.get('category')
if price > 80 and category == '编程':
print(f"昂贵的编程书: {book.find('title').text}")