本文转载至http://blog.csdn.net/jarvischu/article/details/8481510
#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); //--写Int
cvWriteReal(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));//读取顺序流中数据 0
const char* country = cvReadString((CvFileNode*)cvGetSeqElem(seq,1));//读取顺序流中数据 1
cout<<"frame_count:"<<f<<endl<<"width:"<<width<<endl<<"height"<<height<<endl\
<<"name:"<<name<<endl<<"country:"<<country<<endl;
return 0;
}