一些簡單的XML讀寫操作,記之於筆記以備忘
主要功能:
1. 建立XML
2. 向XML中儲存或者是讀取Int float型基本資料
3. 通過建立XML元素,存取複雜的結構如:結構體、矩陣
代碼如下
// BasicExample.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include "opencv2/opencv.hpp"using namespace std;int _tmain(int argc, _TCHAR* argv[]){//建立XML檔案儲存體CvFileStorage* fs = cvOpenFileStorage("jarvischu.xml", 0, //用於儲存的記憶體,如果為NULL,則會使用一個臨時記憶體 CV_STORAGE_WRITE, "GB2312"//編碼 );//寫入資料cvWriteInt(fs,"frame_count",10); //--寫IntcvWriteReal(fs,"pi",3.14); //--寫Float//--寫結構體cvStartWriteStruct(fs,"frame_size",CV_NODE_MAP,"id_size" );// 有名稱(會建立一個標籤)cvWriteInt(fs,"width",320);cvWriteInt(fs,"height",200);cvEndWriteStruct(fs);cvStartWriteStruct(fs,"author_info",CV_NODE_SEQ,"id_author");// 無名稱cvWriteString(fs,0,"JarvisChu");cvWriteString(fs,0,"China");cvEndWriteStruct(fs);//--寫矩陣unsigned char vec[]={1,2,3,4,5,6,7,8,9};CvMat mat = cvMat(3,3,CV_8UC1,vec);cvWrite(fs,"Matrix",&mat);//--寫注釋cvWriteComment(fs,"This is a example for operatoring the xml file",0);//不為0表示放在當前行,0表示新行//釋放cvReleaseFileStorage(&fs);//開啟XML檔案fs = cvOpenFileStorage("jarvischu.xml", 0, //用於儲存的記憶體,如果為NULL,則會使用一個臨時記憶體CV_STORAGE_READ,"GB2312"//編碼 );//讀取資料int f = cvReadIntByName(fs,0,"frame_count",0);//讀取有名字的Int//--讀取元素資料CvFileNode* fn = cvGetFileNodeByName(fs,0,"frame_size"); //先讀取父元素(標籤,節點)int width = cvReadIntByName(fs,fn,"width"); //通過父元素讀取子項目int height = cvReadIntByName(fs,fn,"height");//--讀取元素內的順序資料fn = cvGetFileNodeByName(fs,0,"author_info");//先讀取元素CvSeq* seq = fn->data.seq; //擷取元素的順序流const char* name = cvReadString((CvFileNode*)cvGetSeqElem(seq,0));//讀取順序流中資料 0const char* country = cvReadString((CvFileNode*)cvGetSeqElem(seq,1));//讀取順序流中資料 1cout<<"frame_count:"<<f<<endl<<"width:"<<width<<endl<<"height"<<height<<endl\<<"name:"<<name<<endl<<"country:"<<country<<endl;return 0;}
運行結果如下
jarvischu.xml檔案如下