Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีดึง Nodes เฉพาะใน XML File ด้วย Python

ใช้ XML Library คุณสามารถดึง Node ใดๆ ที่ต้องการจาก XML File ได้ แต่สำหรับการ Extract Node ที่กำหนด คุณต้องรู้จัก XPath การใช้งาน คุณสามารถเรียนรู้เพิ่มเติมเกี่ยวกับ XPath ที่นี่: https://www.w3schools.com/xml/xml_xpath.asp

ตัวอย่าง

สมมติว่าคุณมี XML File โครงสร้างดังนี้:

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

และคุณต้องการ Extract Title Nodes ทั้งหมดที่มี Lang Attribute เป็น 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)