Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lấy node cụ thể từ file XML trong Python (ElementTree + XPath)

Module xml.etree.ElementTree parse XML, dùng XPath-lite (findall, find) để truy xuất node.

XML mẫu

<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>

Trích xuất tất cả <title lang="en">

from xml.etree.ElementTree import ElementTree

tree = ElementTree()
root = tree.parse("my_file.xml")

# XPath: //title[@lang='en'] — mọi title có attr lang='en' ở bất kỳ đâu
for title_elem in root.findall("//title[@lang='en']"):
    print(title_elem.text)
    # Everyday Italian
    # Harry Potter

XPath cơ bản

PatternÝ nghĩa
tagCon trực tiếp
//tagTất cả con cháu (descendant)
./tagCon trực tiếp (explicit)
[@attr='val']Filter attribute
[@attr]Có attribute này
tag[index]Index (1-based): book[1]

Module lxml (mạnh hơn, hỗ trợ XPath 1.0 đầy đủ)

from lxml import etree
root = etree.parse('file.xml')
root.xpath("//title[@lang='en']/text()")