注意:
InsertEndChild与LinkEndChild区别
Insert 系列的函数插入的是结点的副本(包括所有子结点),而 LinkEndChild 插入的就是你创建的对象。
例子 xml 内容:
<?xml version="1.0" encoding="UTF-8" ?>
<Config>
<Database ip="192.168.1.33" port="3306" />
<List>
<Channel count="5">电视剧</Channel>
<Channel count="5">电影</Channel>
</List>
</Config>
写法一:
- void CxmlDlg::MakeXML1()
- {
- // 生成 XML 内容
- TiXmlDocument doc;
- TiXmlElement config("Config");
- TiXmlElement database("Database");
- database.SetAttribute( "ip", "192.168.1.33" );
- database.SetAttribute( "port", 3306 );
- config.InsertEndChild( database );
- TiXmlElement list("List");
- char utf8[32] = {0};
- TiXmlElement channel1("Channel");
- channel1.SetAttribute( "count", 5 );
- MBSToUTF8( utf8, sizeof(utf8), "电视剧" );
- TiXmlText text1( utf8 );
- channel1.InsertEndChild( text1 );
- list.InsertEndChild( channel1 );
- TiXmlElement channel2("Channel");
- channel2.SetAttribute( "count", 5 );
- MBSToUTF8( utf8, sizeof(utf8), "电影" );
- TiXmlText text2( utf8 );
- channel2.InsertEndChild( text2 );
- list.InsertEndChild( channel2 );
- config.InsertEndChild( list );
- doc.InsertEndChild( config );
- TiXmlPrinter printer;
- printer.SetIndent( 0 ); // 设置缩进字符,设为 0 表示不使用缩进。默认为 4个空格,也可设为'\t'
- doc.Accept( &printer );
- char content[256] = {0};
- int size = printer.Size();
- assert( size < sizeof(content) );
- strcpy_s( content, sizeof(content), printer.CStr() );
- }
写法二:
- void CxmlDlg::MakeXML2()
- {
- // 生成 XML 内容
- TiXmlDocument *doc = new TiXmlDocument();
- TiXmlElement *config = new TiXmlElement("Config");
- TiXmlElement *database = new TiXmlElement("Database");
- database->SetAttribute( "ip", "192.168.1.33" );
- database->SetAttribute( "port", 3306 );
- config->LinkEndChild( database );
- TiXmlElement *list = new TiXmlElement("List");
- char utf8[32] = {0};
- TiXmlElement *channel1 = new TiXmlElement("Channel");
- channel1->SetAttribute( "count", 5 );
- MBSToUTF8( utf8, sizeof(utf8), "电视剧" );
- TiXmlText *text1 = new TiXmlText( utf8 );
- channel1->LinkEndChild( text1 );
- list->LinkEndChild( channel1 );
- TiXmlElement *channel2 = new TiXmlElement("Channel");
- channel2->SetAttribute( "count", 5 );
- MBSToUTF8( utf8, sizeof(utf8), "电影" );
- TiXmlText *text2 = new TiXmlText( utf8 );
- channel2->LinkEndChild( text2 );
- list->LinkEndChild( channel2 );
- config->LinkEndChild( list );
- doc->LinkEndChild( config );
- TiXmlPrinter printer;
- printer.SetIndent( 0 );
- doc->Accept( &printer );
- char content[512] = {0};
- int size = printer.Size();
- assert( size < sizeof(content) );
- memcpy( content, printer.CStr(), printer.Size() );
- delete doc;
- }