Python中可以使用lxml
库中的etree
模块来解析数据。下面是一个使用XPath解析数据的简单示例:
from lxml import etree # 创建一个XML文档并解析 xml_datahttps://www.yisu.com/ask/= """""" root = etree.fromstring(xml_data) # 使用XPath选择元素 titles = root.xpath("//title/text()") authors = root.xpath("//author/text()") years = root.xpath("//year/text()") # 打印解析结果 for title, author, year in zip(titles, authors, years): print(f"Title: {title}") print(f"Author: {author}") print(f"Year: {year}") print("---") Python Cookbook David Beazley 2013 Fluent Python Luciano Ramalho 2015
输出结果如下:
Title: Python Cookbook Author: David Beazley Year: 2013 --- Title: Fluent Python Author: Luciano Ramalho Year: 2015 ---
在上面的示例中,使用etree.fromstring()
方法将XML字符串解析为一个Element
对象。然后,可以使用xpath()
方法使用XPath表达式选择相应的元素。最后,使用text
属性获取元素的文本内容。