Computer >> Máy Tính >  >> Lập trình >> Python

Phân tích cú pháp XML bằng Python?

Trình phân tích cú pháp XML của Python cung cấp một trong những cách dễ nhất để đọc và trích xuất thông tin hữu ích từ tệp XML. Trong hướng dẫn ngắn này, chúng ta sẽ xem cách chúng ta có thể phân tích cú pháp tệp XML, sửa đổi và tạo tài liệu XML bằng cách sử dụng API XML của python ElementTree.

API Python ElementTree là một trong những cách dễ nhất để trích xuất, phân tích cú pháp và chuyển đổi dữ liệu XML.

Vì vậy, hãy bắt đầu sử dụng trình phân tích cú pháp Python XML bằng ElementTree:

Ví dụ1

Tạo tệp XML

Đầu tiên, chúng ta sẽ tạo một tệp XML mới với một phần tử và một phần tử con.

#Import required library
import xml.etree.ElementTree as xml

def createXML(filename):
   # Start with the root element
   root = xml.Element("users")
   children1 = xml.Element("user")
   root.append(children1)

   tree = xml.ElementTree(root)
   with open(filename, "wb") as fh:
      tree.write(fh)

if __name__ == "__main__":
   createXML("testXML.xml")

Khi chúng tôi chạy chương trình trên, một tệp mới được tạo có tên “textXML.xml” trong thư mục làm việc mặc định hiện tại của chúng tôi:

Phân tích cú pháp XML bằng Python?

Trong đó có nội dung như:

<users><user /></users>

Xin lưu ý trong khi ghi tệp, chúng tôi đã sử dụng chế độ ‘wb’ .i.e. ghi tệp ở chế độ nhị phân.

Thêm giá trị vào các phần tử XML

Hãy cung cấp một số giá trị cho các phần tử XML trong chương trình ở trên của chúng tôi:

#Import required library
import xml.etree.ElementTree as xml

def createXML(filename):
   # Start with the root element
   root = xml.Element("users")
   children1 = xml.Element("user")
   root.append(children1)

   userId1 = xml.SubElement(children1, "Id")
   userId1.text = "hello"

   userName1 = xml.SubElement(children1, "Name")
   userName1.text = "Rajesh"

   tree = xml.ElementTree(root)
   with open(filename, "wb") as fh:
   tree.write(fh)

if __name__ == "__main__":
   createXML("testXML.xml")

Sau khi chạy chương trình trên, chúng tôi sẽ thấy rằng các phần tử mới được thêm vào các giá trị, chẳng hạn như:

<users>
   <user>
      <Id>hello</Id>
      <Name>Rajesh</Name>
   </user>
</users>

Đầu ra phía trên có vẻ ổn.

Bây giờ chúng ta hãy bắt đầu chỉnh sửa tệp:

Chỉnh sửa dữ liệu XML

Hãy thêm một số dữ liệu vào từ một tệp trong chương trình hiện có của chúng tôi.

newdata.xml

<users>
   <user>
      <id>1a</id>
      <name>Rajesh</name>
      <salary>NA</salary>
   </user>
   <user>
      <id>2b</id>
      <name>TutorialsPoint</name>
      <salary>NA</salary>
   </user>
   <user>
      <id>3c</id>
      <name>Others</name>
      <salary>NA</salary>
   </user>
</users>

Trên đây là tệp xml hiện tại của chúng tôi, hãy cố gắng cập nhật mức lương của từng người dùng:

#Import required library
import xml.etree.ElementTree as ET

def updateET(filename):
   # Start with the root element
   tree = ET.ElementTree(file=filename)
   root = tree.getroot()

   for salary in root.iter('salary'):
      salary.text = '500000'

   tree = ET.ElementTree(root)
   with open("newdata.xml", "wb") as fh:
      tree.write(fh)

if __name__ == "__main__":
   updateET("newdata.xml")

Đầu ra

Phân tích cú pháp XML bằng Python?

Vì vậy, chúng tôi thấy mức lương được thay đổi từ "NA" thành "500000".

Ví dụ:Trình phân tích cú pháp XML của Python

Bây giờ chúng ta hãy viết một chương trình khác sẽ phân tích cú pháp dữ liệu XML có trong tệp và in dữ liệu.

#Import required library
import xml.etree.cElementTree as ET

def parseXML(file_name):
   # Parse XML with ElementTree
   tree = ET.ElementTree(file=file_name)
   print(tree.getroot())
   root = tree.getroot()
   print("tag=%s, attrib=%s" % (root.tag, root.attrib))

   # get the information via the children!
   print("-" * 25)
   print("Iterating using getchildren()")
   print("-" * 25)
   users = root.getchildren()
   for user in users:
      user_children = user.getchildren()
      for user_child in user_children:
         print("%s=%s" % (user_child.tag, user_child.text))

if __name__ == "__main__":
   parseXML("newdata.xml")

Đầu ra

<Element 'users' at 0x0551A5A0>
tag = users, attrib = {}
-------------------------
Iterating using getchildren()
-------------------------
id = 1a
name = Rajesh
salary = 500000
id = 2b
name = TutorialsPoint
salary = 500000
id = 3c
name = Others
salary = 500000