日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

一文詳解測試Python讀寫xml配置文件_python

作者:gc_2299 ? 更新時間: 2022-11-17 編程語言

前言:

xml也是常用的配置文件格式之一,Python中的xml.etree.ElementTree模塊支持解析和創建xml數據。xml格式不再贅述,本文采用參考文獻1中的示例xml數據作為測試數據,

內容如下:

<?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文件時需要用到的對象及函數、屬性如下,完整的代碼及程序運行結果如下所示:

序號 函數或屬性 說明
1 ElementTree.parse 解析包含XML數據的文件名或文件對象,返回一個 ElementTree 實例
2 ElementTree.getroot 返回ElementTree 實例的根節點元素
3 Element.tag 返回元素類型,也即當前標簽的名稱
4 Element.attrib 返回元素的屬性集合
5 Element.text 返回元素內容
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)

構建xml文件時需要用到的對象及函數、屬性如下,完整的代碼及程序運行結果如下所示:

序號 函數或屬性 說明
1 ElementTree.write 將ElementTree實例以 XML 格式寫入到文件,或是以寫入模式打開的 file object
2 ElementTree.Element 創建元素對象
3 Element.set 設置元素的屬性
4 Element.text 設置元素內容
5 Element.append 將指定元素設置為當前元素的子元素
6 ElementTree.SubElement 為給定元素創建新的子元素
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")

除了上述基本的讀寫函數之外,xml.etree.ElementTree模塊還提供有很多十分方便的查找函數,用于在 ElementTree 實例中快速查找指定的元素,詳細介紹請見參考,

除了xml.etree.ElementTree模塊,Python還支持采用xml.dom.minidom讀寫xml文件,后者是文檔對象模型接口的最小化實現,其目標是比完整 DOM 更簡單并且更為小巧,但如果對于DOM 還不十分熟悉,則應考慮改用 xml.etree.ElementTree 模塊來進行 XML 處理。

讀取xml文件時需要用到的對象及函數、屬性如下,完整的代碼及程序運行結果如下所示。從運行結果可以看出,xml.dom.minidom把元素的內容也作為一個節點,即#text,這點來說,沒有xml.etree.ElementTree方便,后者不需要考慮這個。

序號 函數或屬性 說明
1 xml.dom.minidom.parse 根據給定的輸入返回Document對象,輸入參數可以是文件名,也可以是文件類對象,如果xml內容保存在字符串中,可以使用parseString解析xml字符串
2 Document.documentElement 返回文檔根元素
3 Node.nodeName 獲取節點的節點名稱,也即元素類型
4 Node.nodeValue 獲取節點的值
5 Node.attributes 獲取節點的屬性集合
6 Node.childNodes 獲取節點的子節點集合
7 Node.hasAttributes 獲取節點是否有屬性
8 Node.hasChildNodes 獲取節點是否有子節點
9 Attr.name 節點屬性的屬性名稱
10 Attr.value 節點屬性的屬性值
from xml.dom.minidom import parse

def ShowSubNode(curNode):
    print('節點:',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)

構建xml文件時需要用到的對象及函數、屬性如下,完整的代碼及程序運行結果如下所示:

序號 函數或屬性 說明
1 xml.dom.minidom.Document() 創建新的文檔對象
2 Document.createElement 新建元素節點
3 Document.appendChild 添加根節點
4 Element.setAttribute 新建節點屬性,同時設置屬性值
5 Element.appendChild 添加子節點
6 Document.createTextNode 創建文本節點
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")

上述內容即為采用xml.dom.minidom讀寫xml文件的基本用法。測試代碼主要參考自參考[1],[2],其中唯一需要說明的是枚舉節點的屬性集合,百度了很多文章都沒有看到怎么枚舉的,后面直接到xml.dom.minidom的源碼中翻到的用法參考

原文鏈接:https://blog.csdn.net/gc_2299/article/details/127019936

欄目分類
最近更新