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

Phân tích XML (XML Parsing) trong Python?


Parser 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ừ file XML. Trong hướng dẫn ngắn này, chúng ta sẽ xem cách phân tích file XML, sửa đổi và tạo tài liệu XML bằng Python ElementTree XML API.

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

Vậy, hãy bắt đầu với Python XML parser dùng ElementTree:

Ví dụ 1

Tạo file XML

Trước tiên, tạo file XML mới với một element và sub-element.

# Import thư viện cần thiết import xml.etree.ElementTree as xml def createXML(filename):    # Bắt đầu với element gốc    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")

Sau khi chạy chương trình, file mới "testXML.xml" được tạo trong thư mục làm việc mặc định:

Phân tích XML (XML Parsing) trong Python?

Nội dung file giống như:

<users><user /></users>

Lưu ý khi ghi file, ta dùng mode 'wb' (ghi binary).

Thêm giá trị cho các element XML

Hãy gán giá trị cho các element XML trong chương trình trên:

# Import thư viện cần thiết import xml.etree.ElementTree as xml def createXML(filename):    # Bắt đầu với element gốc    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, các element mới được thêm với giá trị:

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

Kết quả trông ổn.

Bây giờ hãy bắt đầu chỉnh sửa file:

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

Thêm dữ liệu từ file vào chương trình hiện 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>

File XML hiện tại như trên, hãy cập nhật salary cho từng user:

# Import thư viện cần thiết import xml.etree.ElementTree as ET def updateET(filename):    # Bắt đầu với element gốc    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")

Kết quả

Phân tích XML (XML Parsing) trong Python?

Thấy salary thay đổi từ 'NA' thành '500000'.

Ví dụ: Python XML Parser

Viết chương trình phân tích dữ liệu XML trong file và in ra dữ liệu.

# Import thư viện cần thiết import xml.etree.cElementTree as ET def parseXML(file_name):    # Parse XML với ElementTree    tree = ET.ElementTree(file=file_name)    print(tree.getroot())    root = tree.getroot()    print("tag=%s, attrib=%s" % (root.tag, root.attrib))    # Lấy thông tin qua các 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")

Kết quả

<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