tree = etree.parse('example.xml')
root = tree.getroot()
遍历根节点的子元素
for element in root:print(f"Element tag: {element.tag}, Element text: {element.text}")
使用XPath表达式查找元素
element = root.find(".//subelement")if element isnotNone:print(f"Found element: {element.tag}, Element text: {element.text}")
获取元素的属性
element = root.find("element1")if element isnotNone:
attribute_value = element.get("attribute_name")print(f"Attribute value: {attribute_value}")
修改元素的文本内容
element = root.find("element1")if element isnotNone:
element.text ="New text"#把修改后的内容写回原文件#tree.write('output.xml', pretty_print=True, encoding='utf-8')
添加新元素
new_element = etree.Element("new_element")
new_element.text ="New element text"
root.append(new_element)
for book in books:
title = book.find("title").text
author = book.find("author").text
price = book.find("price").text
print("书名:", title)print("作者:", author)print("价格:", price)print()