一些简单的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",//用于存储的内存,如果为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,"JarvisChu"); cvWriteString(fs,"China"); cvEndWriteStruct(fs); //--写矩阵 unsigned char vec[]={1,2,3,4,5,6,7,8,9}; CvMat mat = cvMat(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",则会使用一个临时内存 CV_STORAGE_READ,"GB2312"//编码 ); //读取数据 int f = cvReadIntByName(fs,0);//读取有名字的Int //--读取元素数据 CvFileNode* fn = cvGetFileNodeByName(fs,"frame_size"); //先读取父元素(标签,节点) int width = cvReadIntByName(fs,fn,"width"); //通过父元素读取子元素 int height = cvReadIntByName(fs,"height"); //--读取元素内的顺序数据 fn = cvGetFileNodeByName(fs,"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; }
运行结果如下
jarvischu.xml文件如下
原文链接:https://www.f2er.com/xml/294719.html