XML là một ngôn ngữ đánh dấu mở rộng, được sử dụng để định nghĩa và lưu trữ dữ liệu. Dưới đây là cách sử dụng Python để đọc các tệp XML.
Hiểu về XML
Một ví dụ đơn giản của tệp XML:
<?xml version="1.0" encoding="utf-8"?>
<danhmuc>
<maxid>4</maxid>
<login username="thuvien" passwd='654321'>
<tieu_de>Python</tieu_de>
<phan_tu id="4">
<tieu_de>Kiểm thử</tieu_de>
</phan_tu>
</login>
<phan_tu id="2">
<tieu_de>Django</tieu_de>
</phan_tu>
</danhmuc>
Đọc tệp XML với Python
Sử dụng thư viện xml.dom.minidom để xử lý tệp XML.
<code><pre>#coding=utf-8
import xml.dom.minidom
# Mở tệp XML
doc = xml.dom.minidom.parse('danhmuc.xml')
# Lấy đối tượng phần tử tài liệu
goc = doc.documentElement
print(goc.nodeName)
print(goc.nodeType)
</pre></code>
Lấy các thẻ con
Để lấy các thẻ con từ một phần tử:
<code><pre>#coding=utf-8
import xml.dom.minidom
# Mở tệp XML
doc = xml.dom.minidom.parse('danhmuc.xml')
# Lấy đối tượng phần tử tài liệu
goc = doc.documentElement
ds_phan_tu = goc.getElementsByTagName('maxid')
pt = ds_phan_tu[0]
print(pt.nodeName)
ds_login = goc.getElementsByTagName('login')
lg = ds_login[0]
print(lg.nodeName)
</pre></code>
Lấy giá trị thuộc tính của thẻ
Để lấy giá trị thuộc tính của một thẻ:
<code><pre>#coding=utf-8
import xml.dom.minidom
# Mở tệp XML
doc = xml.dom.minidom.parse('danhmuc.xml')
# Lấy đối tượng phần tử tài liệu
goc = doc.documentElement
ds_login = goc.getElementsByTagName('login')
lg = ds_login[0]
ten_nguoi_dung = lg.getAttribute("username")
print(ten_nguoi_dung)
mat_khau = lg.getAttribute("passwd")
print(mat_khau)
</pre></code>
Lấy dữ liệu giữa các cặp thẻ
Có nhiều cách để lấy dữ liệu giữa các cặp thẻ:
Phương pháp 1
<code><pre>#coding=utf-8
import xml.dom.minidom
# Mở tệp XML
doc = xml.dom.minidom.parse('danhmuc.xml')
# Lấy đối tượng phần tử tài liệu
goc = doc.documentElement
ds_tieu_de = doc.getElementsByTagName('tieu_de')
td1 = ds_tieu_de[0]
print(td1.firstChild.data)
td2 = ds_tieu_de[1]
print(td2.firstChild.data)
</pre></code>
Phương pháp 2
<code><pre>#coding=utf-8
from xml.etree import ElementTree as ET
doc_tree = ET.parse('danhmuc.xml')
phan_tu = doc_tree.findall('./login/phan_tu')
for pt in phan_tu:
for child in pt:
print(child.tag, ':', child.text)
</pre></code>