一文詳解測試Python讀寫xml配置文件
前言:
xml也是常用的配置文件格式之一,Python中的xml.etree.ElementTree模塊支持解析和創(chuàng)建xml數(shù)據(jù)。xml格式不再贅述,本文采用參考文獻(xiàn)1中的示例xml數(shù)據(jù)作為測試數(shù)據(jù),
內(nèi)容如下:
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>讀取xml文件時需要用到的對象及函數(shù)、屬性如下,完整的代碼及程序運(yùn)行結(jié)果如下所示:
| 序號 | 函數(shù)或?qū)傩?/th> | 說明 |
|---|---|---|
| 1 | ElementTree.parse | 解析包含XML數(shù)據(jù)的文件名或文件對象,返回一個 ElementTree 實(shí)例 |
| 2 | ElementTree.getroot | 返回ElementTree 實(shí)例的根節(jié)點(diǎn)元素 |
| 3 | Element.tag | 返回元素類型,也即當(dāng)前標(biāo)簽的名稱 |
| 4 | Element.attrib | 返回元素的屬性集合 |
| 5 | Element.text | 返回元素內(nèi)容 |
import xml.etree.ElementTree as ET
def ShowSubElement(curElement,level):
print(level,' tag:',curElement.tag,'attribute:', curElement.attrib,'text:',curElement.text)
for child in curElement:
ShowSubElement(child,level+1)
tree = ET.parse('test.xml')
level=1
root = tree.getroot()
ShowSubElement(root,level)
構(gòu)建xml文件時需要用到的對象及函數(shù)、屬性如下,完整的代碼及程序運(yùn)行結(jié)果如下所示:
| 序號 | 函數(shù)或?qū)傩?/th> | 說明 |
|---|---|---|
| 1 | ElementTree.write | 將ElementTree實(shí)例以 XML 格式寫入到文件,或是以寫入模式打開的 file object |
| 2 | ElementTree.Element | 創(chuàng)建元素對象 |
| 3 | Element.set | 設(shè)置元素的屬性 |
| 4 | Element.text | 設(shè)置元素內(nèi)容 |
| 5 | Element.append | 將指定元素設(shè)置為當(dāng)前元素的子元素 |
| 6 | ElementTree.SubElement | 為給定元素創(chuàng)建新的子元素 |
import xml.etree.ElementTree as ET
root = ET.Element('root')
root.set('ver','2.0')
classA=ET.Element('classA')
root.append(classA)
classA.set("master","張三")
classA.set("grade","一年級")
studentA=ET.Element('studentA')
classA.append(studentA)
studentA.text='小米'
classB=ET.SubElement(root,'classB')
classB.set("master","李四")
classB.set("grade","三年級")
studentB=ET.SubElement(classB,'studentB')
studentB.text='小明'
tree = ET.ElementTree(root)
tree.write("writetest.xml")
除了上述基本的讀寫函數(shù)之外,xml.etree.ElementTree模塊還提供有很多十分方便的查找函數(shù),用于在 ElementTree 實(shí)例中快速查找指定的元素,詳細(xì)介紹請見參考,
除了xml.etree.ElementTree模塊,Python還支持采用xml.dom.minidom讀寫xml文件,后者是文檔對象模型接口的最小化實(shí)現(xiàn),其目標(biāo)是比完整 DOM 更簡單并且更為小巧,但如果對于DOM 還不十分熟悉,則應(yīng)考慮改用 xml.etree.ElementTree 模塊來進(jìn)行 XML 處理。
讀取xml文件時需要用到的對象及函數(shù)、屬性如下,完整的代碼及程序運(yùn)行結(jié)果如下所示。從運(yùn)行結(jié)果可以看出,xml.dom.minidom把元素的內(nèi)容也作為一個節(jié)點(diǎn),即#text,這點(diǎn)來說,沒有xml.etree.ElementTree方便,后者不需要考慮這個。
| 序號 | 函數(shù)或?qū)傩?/th> | 說明 |
|---|---|---|
| 1 | xml.dom.minidom.parse | 根據(jù)給定的輸入返回Document對象,輸入?yún)?shù)可以是文件名,也可以是文件類對象,如果xml內(nèi)容保存在字符串中,可以使用parseString解析xml字符串 |
| 2 | Document.documentElement | 返回文檔根元素 |
| 3 | Node.nodeName | 獲取節(jié)點(diǎn)的節(jié)點(diǎn)名稱,也即元素類型 |
| 4 | Node.nodeValue | 獲取節(jié)點(diǎn)的值 |
| 5 | Node.attributes | 獲取節(jié)點(diǎn)的屬性集合 |
| 6 | Node.childNodes | 獲取節(jié)點(diǎn)的子節(jié)點(diǎn)集合 |
| 7 | Node.hasAttributes | 獲取節(jié)點(diǎn)是否有屬性 |
| 8 | Node.hasChildNodes | 獲取節(jié)點(diǎn)是否有子節(jié)點(diǎn) |
| 9 | Attr.name | 節(jié)點(diǎn)屬性的屬性名稱 |
| 10 | Attr.value | 節(jié)點(diǎn)屬性的屬性值 |
from xml.dom.minidom import parse
def ShowSubNode(curNode):
print('節(jié)點(diǎn):',curNode.nodeName,":",curNode.nodeValue)
if curNode.nodeName=='#text':
return
if curNode.hasAttributes:
for attr in curNode.attributes.values():
print('屬性:',attr.name,':',attr.value)
if curNode.hasChildNodes:
for child in curNode.childNodes:
ShowSubNode(child)
doc = parse('test.xml')
root = doc.documentElement
ShowSubNode(root)
構(gòu)建xml文件時需要用到的對象及函數(shù)、屬性如下,完整的代碼及程序運(yùn)行結(jié)果如下所示:
| 序號 | 函數(shù)或?qū)傩?/th> | 說明 |
|---|---|---|
| 1 | xml.dom.minidom.Document() | 創(chuàng)建新的文檔對象 |
| 2 | Document.createElement | 新建元素節(jié)點(diǎn) |
| 3 | Document.appendChild | 添加根節(jié)點(diǎn) |
| 4 | Element.setAttribute | 新建節(jié)點(diǎn)屬性,同時設(shè)置屬性值 |
| 5 | Element.appendChild | 添加子節(jié)點(diǎn) |
| 6 | Document.createTextNode | 創(chuàng)建文本節(jié)點(diǎn) |
| 7 | Document.writexml | 保存xml到文件 |
import xml.dom.minidom
doc = xml.dom.minidom.Document()
root=doc.createElement("root")
root.setAttribute('ver','2.0')
doc.appendChild(root)
classA=doc.createElement('classA')
root.appendChild(classA)
classA.setAttribute("master","張三")
classA.setAttribute("grade","一年級")
studentA=doc.createElement('studentA')
classA.appendChild(studentA)
studentA.appendChild(doc.createTextNode('小米'))
classB=doc.createElement('classB')
root.appendChild(classB)
classB.setAttribute("master","李四")
classB.setAttribute("grade","三年級")
studentB=doc.createElement('studentB')
classB.appendChild(studentB)
studentB.appendChild(doc.createTextNode('小明'))
with open("writetest1.xml", "w", encoding='utf-8') as f:
doc.writexml(f, indent='\t', addindent='\t', newl='\n', encoding="utf-8")
上述內(nèi)容即為采用xml.dom.minidom讀寫xml文件的基本用法。測試代碼主要參考自參考[1],[2],其中唯一需要說明的是枚舉節(jié)點(diǎn)的屬性集合,百度了很多文章都沒有看到怎么枚舉的,后面直接到xml.dom.minidom的源碼中翻到的用法參考
到此這篇關(guān)于一文詳解測試Python讀寫xml配置文件的文章就介紹到這了,更多相關(guān)Python讀寫xml配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python opencv圖片編碼為h264文件的實(shí)例
今天小編就為大家分享一篇python opencv圖片編碼為h264文件的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python腳本實(shí)現(xiàn)自動刪除C盤臨時文件夾
在日常使用電腦的過程中,臨時文件夾往往會積累大量的無用數(shù)據(jù),占用寶貴的磁盤空間,下面我們就來看看Python如何通過腳本實(shí)現(xiàn)自動刪除C盤臨時文件夾吧2025-01-01
python的getattr和getattribute攔截內(nèi)置操作實(shí)現(xiàn)
在Python中,getattr和getattribute是用于動態(tài)屬性訪問和自定義屬性訪問行為的重要工具,本文主要介紹了python的getattr和getattribute攔截內(nèi)置操作實(shí)現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-01-01
Python中Playwright模塊進(jìn)行自動化測試的實(shí)現(xiàn)
playwright是由微軟開發(fā)的Web UI自動化測試工具,本文主要介紹了Python中Playwright模塊進(jìn)行自動化測試的實(shí)現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-12-12
Python進(jìn)階之使用selenium爬取淘寶商品信息功能示例
這篇文章主要介紹了Python進(jìn)階之使用selenium爬取淘寶商品信息功能,結(jié)合實(shí)例形式詳細(xì)分析了Python使用selenium與requests模塊爬取淘寶商品信息的相關(guān)操作技巧,需要的朋友可以參考下2019-09-09
總結(jié)python 三種常見的內(nèi)存泄漏場景
這篇文章主要介紹了總結(jié)python 三種常見的內(nèi)存泄漏場景,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-11-11
詳解Python logging調(diào)用Logger.info方法的處理過程
這篇文章主要介紹了詳解Python logging調(diào)用Logger.info方法的處理過程,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02

