Ghi (write) file XML với Python

Đây là bài 43/54 bài của series môn học Ngôn ngữ lập trình Python

Trước khi đọc bài này, các bạn nên đọc bài Đọc (read) file XML với Python để biết khái niệm cơ bản của XML cũng như cách đọc một file XML. Với những kiến thức đó, các bạn sẽ dễ dàng hiểu được những cách ghi (write) file XML trong Python.

1. Ghi (write) file XML với ElementTree

Module ElementTree là một công cụ tuyệt với để giúp ghi dữ liệu vào file XML. Các bước để tạo file XML và ghi dữ liệu vào file XML với ElementTree như sau:

Bước 1. Tạo ra một thẻ root trong file XML.

Bước 2. Sử dụng hàm SubElement() để tạo ra các thẻ con nằm trong thẻ root với cú pháp sau:

SubElement(parent, tag, attrib={}, **extra)

Trong đó, parent là tên của thẻ root, tag là tên của thẻ con nằm trong thẻ root. attribmột dictionary chứa các thuộc tính của thẻ con. extra chứa những thuộc tính bổ sung.

Hàm SubElement() sẽ trả về một đối tượng là một thẻ mới.

Bước 3. Chúng ta có thể sử dụng hàm set() để thêm các thuộc tính cho thẻ mới được tạo ra. Text của một thẻ được gán với thuộc tính text.

import xml.etree.ElementTree as ET

# create the file structure
data = ET.Element('data')

items = ET.SubElement(data, 'items')

item1 = ET.SubElement(items, 'item')
item2 = ET.SubElement(items, 'item')
item3 = ET.SubElement(items, 'item')

item1.set('name', 'item1')
item1.set('price', '5')
item2.set('name','item2')
item2.set('price','15')
item3.set('name', 'item3')
item3.set('price','20')

item1.text = 'book'
item2.text = 'chair'
item3.text = 'window'

# create a new XML file
mydata = ET.tostring(data, encoding='unicode')
myxmlfile = open("items2.xml", "w")
myxmlfile.write(mydata)
myxmlfile.close()
Kết quả nội dung của file items2.xml được tạo ra
<data><items><item name="item1" price="5">book</item><item name="item2" price="15">chair</item><item name="item3" price="20">window</item></items></data>

2. Ghi (write) file XML với minidom

Với minidom, các thẻ trong file XML được xem như là các đối tượng (object). Các bước để tạo file XML và ghi dữ liệu vào file XML với minidom như sau:

Bước 1. Sử dụng hàm Document() để tạo một tài liệu XML.

Bước 2. Tạo một đối tượng gốc đại diện cho thẻ root trong file XML bằng cách dùng hàm createElement(). Nối thẻ root vào file XML bằng hàm appendChild().

Bước 3. Tạo các đối tượng con đại diện cho các thẻ con nằm trong thẻ root cũng với hàm createElement(). Sử dụng hàm setAttribute() để thiết lập thuộc tính (nếu có) cho các thẻ con.

Bước 4. Nối các thẻ con vào file XML bằng hàm appendChild().

from xml.dom import minidom

# create a xml document  
root = minidom.Document()
# create data tag as root tag
data = root.createElement('data')
root.appendChild(data)

# create child tag of data tag
items = root.createElement('items')
data.appendChild(items)

# create child tag of items
item1 = root.createElement('item')
item1.setAttribute('name', 'item1')
item1.setAttribute('price', '5')
item1.Text = 'book'
items.appendChild(item1)
item1Text = root.createTextNode("book")
item1.appendChild(item1Text)

item2 = root.createElement('item')
item2.setAttribute('name', 'item2')
item2.setAttribute('price', '15')
items.appendChild(item2)
item2Text = root.createTextNode("chair")
item2.appendChild(item2Text)

item3 = root.createElement('item')
item3.setAttribute('name', 'item3')
item3.setAttribute('price', '20')
items.appendChild(item3)
item3Text = root.createTextNode("window")
item3.appendChild(item3Text)

# create a new XML file
mydata = root.toprettyxml(indent ="\t")
myxmlfile = open("items2.xml", "w")
myxmlfile.write(mydata)
myxmlfile.close()
Kết quả nội dung của file items2.xml được tạo ra
<?xml version="1.0" ?>
<data>
    <items>
        <item name="item1" price="5">book</item>
        <item name="item2" price="15">chair</item>
        <item name="item3" price="20">window</item>
    </items>
</data>

3. Ghi (write) file XML với BeautifulSoup

Chúng ta cũng có thể sử dụng BeautifulSoup để tạo và ghi một file XML. Các bước để tạo file XML và ghi dữ liệu vào file XML với BeautifulSoup như sau:

Bước 1. Sử dụng hàm BeautifulSoup(features='xml') để tạo một tài liệu XML rỗng.

Bước 2. Tạo một tag mới bằng cách dùng hàm new_tag(). Nối tag mới vào file XML bằng hàm append().

Bước 3. Tạo các thẻ con nằm trong thẻ đã tạo cũng với hàm new_tag(). Sử dụng thuộc tính string để thiết lập văn bản (text) cho các thẻ con. Thiết lập thuộc tính cho thẻ con bằng cách sử dụng dấu ngoặc vuông [] và gán giá trị cho thuộc tính đó.

Bước 4. Nối các thẻ con vào file XML bằng hàm append().

from bs4 import BeautifulSoup

# create an empty xml document
soup = BeautifulSoup(features='xml')

# create data tag as root tag
data = soup.new_tag("data")
soup.append(data)

# create child tag of data tag
items = soup.new_tag("items")
data.append(items)

# create child tag of items
item1 = soup.new_tag('item')
item1.string = "book"
item1["name"] = "item1"
item1["price"] = "5"
items.append(item1)
item2 = soup.new_tag('item')
item2.string = "chair"
item2["name"] = "item2"
item2["price"] = "15"
items.append(item2)
item3 = soup.new_tag('item')
item3.string = "window"
item3["name"] = "item3"
item3["price"] = "20"
items.append(item3)

# create a new XML file
myxmlfile = open("items2.xml", "w")
myxmlfile.write(soup.prettify())
myxmlfile.close()
Kết quả nội dung của file items2.xml được tạo ra
<?xml version="1.0" encoding="utf-8"?>
<data>
 <items>
  <item name="item1" price="5">
   book
  </item>
  <item name="item2" price="15">
   chair
  </item>
  <item name="item3" price="20">
   window
  </item>
 </items>
</data>
5/5 - (1 bình chọn)
Bài trước và bài sau trong môn học<< Đọc (read) file XML với PythonĐọc (read) file JSON với Python >>
Chia sẻ trên mạng xã hội:

Trả lời

Lưu ý:

1) Vui lòng bình luận bằng tiếng Việt có dấu.

2) Khuyến khích sử dụng tên thật và địa chỉ email chính xác.

3) Mọi bình luận trái quy định sẽ bị xóa bỏ.