如何在Python中的xml文件中获取特定的节点?
使用xml库,您可以从xml文件中获取所需的任何节点。但是对于提取给定的节点,您需要知道如何使用xpath来获取它。您可以在此处了解有关XPath的更多信息:https://www.w3schools.com/xml/xml_xpath.asp。
示例
例如,假设您有一个具有以下结构的xml文件,
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>并且您想要提取具有lang属性en的所有标题节点,那么您将获得代码-
from xml.etree.ElementTree import ElementTree
tree = ElementTree()root = tree.parse("my_file.xml")
for node in root.findall("//title[@lang='en']"):
for type in node.getchildren():
print(type.text)热门推荐
8 薛之谦祝福语简短
10 简短中秋祝福语朋友结婚
11 2026祝福语简短创意牛
12 14年祝福语简短情话
13 小寒健康祝福语大全简短
14 宝宝生病简短祝福语大全
15 恋爱祝福语大全简短搞笑
16 婚礼祝福语简短情话文案
17 孩子满月随礼简短祝福语
18 周二祝福语大全简短