python 常用包之xml文件處理


1,處理xml的包

from xml.etree import ElementTree as ET

2,如何寫出xml文件

xml文件和html中的元素很像,有父級子集之說,

root = ET.Element('opencv_storage')    #創建根元素,根元素的變量名叫root,元素名字叫opencv_storage
    person1 = ET.SubElement(root, 'cameraId')    #在根元素上創建子元素,子元素的變量名叫person1,元素名叫cameraID
    person1.text="camera url"    #persion1對應的元素內容是"camera url" 
    intr = ET.SubElement(root, 'intrinsic_parameters', {'type_id':'opencv-matrix'})    #在根元素上再加一個子元素叫intr,元素有個屬性是“type_id",屬性的內容是'opencv-matrix'
    rows = ET.SubElement(intr, 'rows')    #intr元素上加子元素,以下同理
    rows.text="3"
    cols=ET.SubElement(intr, 'cols')
    cols.text="3"
    dt=ET.SubElement(intr, 'dt')
    dt.text="d"
    data=ET.SubElement(intr, 'data')
    data.text=" 1 2 3 1 2 3 1 2 3 "
    dist=ET.SubElement(root, 'distortion_parametes',{"type_id":"opencv-matrix"})
    rows2=ET.SubElement(dist, 'rows')
    rows2.text="1"
    cols2=ET.SubElement(dist, 'cols')
    cols2.text="5"
    dt2=ET.SubElement(dist, 'dt')
    dt2.text='d'
    data2=ET.SubElement(dist, 'data')
    data2.text="1 2 3 4 5"
    tree = ET.ElementTree(root)#將根目錄轉化為xml樹狀結構(即ElementTree對象) 
    ET.dump(root)#在終端顯示整個xml內容
    tree.write('sample.xml', encoding="utf-8", xml_declaration=True)#寫入xml文件 

sample.xml的文件內容:

<?xml version='1.0' encoding='utf-8'?>
<opencv_storage>
<cameraId>camera url</cameraId>

<intrinsic_parameters type_id="opencv-matrix">
<rows>3</rows>
<cols>3</cols>
<dt>d</dt>
<data>1 2 3 1 2 3 1 2 3 </data>
</intrinsic_parameters>

<distortion_parametes type_id="opencv-matrix">
<rows>1</rows>
<cols>5</cols>
<dt>d</dt>
<data>1 2 3 4 5</data>
</distortion_parametes>
</opencv_storage>

3,如何解析xml文件

以解析上一個sample.xml為例:

    try:
        tree = ET.parse("./sample.xml”)
        root = tree.getroot()
    except Exception as e:
        print("xml文件打開錯誤",e)
        return -1
    for i in root:    #可以直接遍歷父元素來獲取子元素
        if i.tag == "intrinsic_parameters":    #i.tag是元素名
            matrix_height=int(i.find("rows").text)    #i.find("rows")獲取子元素中名字叫rows的元素,不會遞歸查找,如有多個只獲取第一個。findall可以獲取多個,i.text()獲取某元素的內容
            matrix_width=int(i.find("cols").text)
            matrix_str=i.find("data").text
        if i.tag == "distortion_parametes":
            coefs_height=int(i.find("rows").text)
            coefs_width=int(i.find("cols").text)
            coefs_str=i.find("data").text

    #獲取到元素內容以后可以自行解析

補充:

root.attrib:獲取屬性

Element.get():訪問標簽的屬性值

Element.set():添加和修改標簽的屬性和屬性值。 

Element.append():添加孩子節點

4,拓展

這樣的xml:sample.xml

<?xml version="1.0"?>
<actors xmlns:fictional="http://characters.example.com"
        xmlns="http://people.example.com">
    <actor>
        <name>John Cleese</name>
        <fictional:character>Lancelot</fictional:character>
        <fictional:character>Archie Leach</fictional:character>
    </actor>
    <actor>
        <name>Eric Idle</name>
        <fictional:character>Sir Robin</fictional:character>
        <fictional:character>Gunther</fictional:character>
        <fictional:character>Commander Clement</fictional:character>
    </actor>
</actors>

通過這個操作:

from xml.etree import ElementTree as ET
tree = ET.parse('sample.xml')
root = tree.getroot()
ns = {'real_person': 'http://people.example.com',
      'role': 'http://characters.example.com'}

for actor in root.findall('real_person:actor', ns):
    name = actor.find('real_person:name', ns)
    print(name.text)
    for char in actor.findall('role:character', ns):
        print(' |-->', char.text)

生成如下代碼:(還沒看懂)

可參考

John Cleese
 |--> Lancelot
 |--> Archie Leach
Eric Idle
 |--> Sir Robin
 |--> Gunther
 |--> Commander Clement

 5,opencv自帶的xml處理器

opencv自帶一個文件處理器,名字叫cv2.FileStorage,用法如下:

import cv2
import numpy as np

#從xml文件中讀出
aa=cv2.FileStorage("./hehe.xml",cv2.FileStorage_READ)
print(aa.getNode("intrinsic_parameters").mat())

#寫入xml文件
fs = cv2.FileStorage('./hehe.xml', cv2.FileStorage_WRITE)
aa=range(9)
bb=range(5)
camera_matrix=np.array(aa).reshape(3,3)
dist_coefs=np.array(bb).reshape(1,5)
fs.write("intrinsic_parameters", camera_matrix)
fs.write("distortion_parametes", dist_coefs)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM