我想生成格式的 XML,
<Library>
<ConfigParams>
<parameter name= "name1"> abc </parameter>
<parameter name= "name2"> def </parameter>
</ConfigParams>
<Books>
<Book>
<name>xyz</name>
<title>jlkjlkj</title>
<Parameters>
<parameter name= "name3">name1 </parameter>
<parameter name= "name4"> name4 </parameter>
</Parameters>
</Book>
<Book>
<name>xyzkjk</name>
<title>jlj</title>
<Parameters>
<parameter name= "name8">name22 </parameter>
<parameter name= "name7"> name44 </parameter>
</Parameters>
</Book>
</Books>
</Library>
为此,我决定使用 TinyXML:
我创建了以下类:
class Param
{
public:
string value;
string name;
Param();
Param( string value, string name)
{
this->value=value;
this->name=name;
}
};
class Parameters
{
public:
list<Param> param;
Parameters();
Parameters(list<Param> param)
{
this->param = param;
}
};
class Book
{
public:
string name;
string title;
Parameters parameters;
Book();
Book(string name, string title, Parameters parameters)
{
this->name = name;
this->title = title;
this->parameters = parameters;
}
};
class Books
{
public:
list<Book> books;
Books();
Books(list<Book> books)
{
this->books = books;
}
};
class Library
{
public:
Parameters configParams;
Books books;
Library();
Library(Parameters configparams, Books books)
{
this->configParams=configparams;
this->books=books;
}
void save(const char* Filename);
};
class ConfigParams
{
public:
Parameters configparams;
ConfigParams();
ConfigParams(Parameters configparams)
{
this->configparams = configparams;
}
};
现在,当我想为这个类层次结构生成一个 Xml 文档时,
void Library::save(const char* Filename)
{
TiXmlDocument doc;
TiXmlElement* msg;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
doc.LinkEndChild( decl );
TiXmlElement * root = new TiXmlElement("Library");
doc.LinkEndChild( root );
//block configparams
{
TiXmlElement * configparams= new TiXmlElement( "ConfigParams" );
root->LinkEndChild( configparams );
Param param1=Param("name1", "abc");
Param param2=Param("name2" ,"def");
list<Param> params =list<Param>();
list <Param>::iterator Iter;
Iter=params.begin();
params.insert(Iter,param1);
params.insert(Iter,param2);
Parameters parameters=Parameters(params);
ConfigParams configparams=ConfigParams(parameters);
但是,我不知道如何使用 TinyXml 将这些类添加到 XML 表单中?