如何在Python中获取xml文件中的特定节点?

如何在Python中获取xml文件中的特定节点?

使用xml库,您可以从xml文件中获取任何想要的节点。但要提取一个给定的节点,您需要知道如何使用xpath来获取它。您可以在这里学习更多关于XPath的知识: https://www.w3schools.com/xml/xml_xpath.asp.

阅读更多:Python 教程

示例

例如,假设您有一个带有以下结构的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)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程