输入输出XML和YAML文件

前端之家收集整理的这篇文章主要介绍了输入输出XML和YAML文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "iostream"
#include "string"

using namespace std;
using namespace cv;


class MyData
{

public:
	MyData(): A(0),X(0),id()
	{}
	explicit MyData(int) : A(97),X(CV_PI),id("mydata1234")// explicit构造函数是用来防止隐式转换的
	{} 
    void write( FileStorage& fs ) const{  //对自定义类进行写序列化
		fs << "{" << "A" << A << "X" << X << "id" << id << "}";
	}
	void read( const FileNode& node ){  //从序列读取自定义类
		A = (int)(node["A"]);
		X = (int)(node["X"]);
		id = (string)(node["id"]);
	}
public:
	int A;
	double X;
	string id;
	

};

void write(FileStorage& fs,const std::string&,const MyData& x)
{
	x.write(fs);
}
void read(const FileNode& node,MyData& x,const MyData& default_value = MyData()){
	if(node.empty())
		x = default_value;
	else
		x.read(node);
}

ostream& operator << ( ostream& out,const MyData& m){  //对"<<"运算符的重载,返回值类型为引用,将数据显示到屏幕上用到
	out << "{ id = " << m.id << ",";
	out << "X = " << m.X << ",";
	out << "A = " << m.A << "}";
	return out;
}

int main(int argc,char* argv[])
{
	if ( argc != 2)
	{
		return -1;
	}
	string filename = argv[1];
	{ //write
		Mat R = Mat_<uchar>::eye( 3,3 );
		Mat T = Mat_<double>::zeros( 3,1);
		MyData m(1); //显式调用MyData的构造函数,初始化的时候调用有参数的那个
		FileStorage fs( filename,FileStorage::WRITE );
		fs << "iterationNr" << 100;
		fs << "string" << "[";  //对于序列,在第一个元素前输出”[“字符,并在最后一个元素后输出”]“字符
		fs << "image1.jpg" << "Awesomeness" << "baboon.jpg";
		fs << "]";

		fs << "Mapping";  //对于maps使用相同的方法,但采用”{“和”}“作为分隔符
		fs << "{" << "one" << 1;  //
		fs << "two" << 2 << "}";

		fs << "R" << R;
		fs << "T" << T;

		fs << "MyData" << m;  //写入自己的数据

		fs.release();
		cout << "Write Done" << endl;  //写入完成
	}
	{ //read
		cout << endl << "Reading" << endl;
		FileStorage fs;
		fs.open( filename,FileStorage::READ );
		int itNr;
		itNr = (int)fs["iterationNr"];
		cout << itNr;

		if ( !fs.isOpened() )
		{
			cout << "Fail to open" << filename <<endl;
			return -1;
		}

		FileNode n = fs["string"];
		if ( n.type() != FileNode::SEQ )
		{
			cout << "strings is not a sequence! FAIL" << endl;
			return -1;
		}

		FileNodeIterator it = n.begin(),it_end = n.end();
		for (;it != it_end; ++it)
		{
			cout << (string)*it << endl;
		}

		n = fs["Mapping"]; //将节点定位到Maping处
		cout << "one" << (int)(n["one"]) << ";";
		cout << "two" << (int)(n["two"]) << endl;

		MyData m; //读取自己的数据结构
		Mat R,T;
		fs["R"] >> R;
		fs["T"] >> T;
		fs["MyData"] >> m;
		cout << endl << "R=" << R << endl;
		cout  << "T=" << endl << T << endl << endl;
		cout  << "MyData=" << endl << m << endl << endl;

		fs["NonExistint"]  >> m; //尝试读取一个不存在的值
		cout << endl << "NonExisting=" << endl << m <<endl; 


	}
	cout << endl 
		<< "Tip: Open up " << filename << " with a text editor to see the serialized data." << endl;
	return 0;
}
原文链接:https://www.f2er.com/xml/296716.html

猜你在找的XML相关文章