练习TinyXml的写操作

来源:互联网 发布:冒险岛怪物数据库 编辑:程序博客网 时间:2024/05/02 02:55
int Write(){    TiXmlDocument doc ;    TiXmlDeclaration *declare =new TiXmlDeclaration("1.0" , "","");    doc.LinkEndChild(declare);    doc.LinkEndChild(new TiXmlComment("群英集团人力资源表"));    TiXmlElement *root    = new TiXmlElement("群英集团");        TiXmlElement *sub    = new TiXmlElement("员工");    sub->SetAttribute("ID" , "011");                // 向sub中添加属性    sub->SetAttribute("职位" , "技术总监");    TiXmlElement *child = new TiXmlElement("姓名");    // 建立子元素    TiXmlText *content =new TiXmlText("虚竹");        // 建立文本    child->LinkEndChild(content);                    // 将建立的文本追加到child所指的子元素中    sub->LinkEndChild(child);                        // 将child追加到sub中,以作为子元素    root->LinkEndChild(sub);                        // 将sub追加到root中,以作为子元素    sub    = new TiXmlElement("员工");    sub->SetAttribute("ID" , "029");    sub->SetAttribute("职位" , "技术总监");    child = new TiXmlElement("姓名");    content =new TiXmlText("乔峰");    child->LinkEndChild(content);    sub->LinkEndChild(child);        root->LinkEndChild(sub);    sub    = new TiXmlElement("员工");    sub->SetAttribute("ID" , "100");    sub->SetAttribute("职位" , "总架构师");    child = new TiXmlElement("姓名");    content =new TiXmlText("扫地僧");    child->LinkEndChild(content);    sub->LinkEndChild(child);        root->LinkEndChild(sub);    sub    = new TiXmlElement("员工");    sub->SetAttribute("ID" , "101");    sub->SetAttribute("职位" , "公关部经理");    child = new TiXmlElement("姓名");    content =new TiXmlText("韦小宝");    child->LinkEndChild(content);    sub->LinkEndChild(child);        root->LinkEndChild(sub);    sub    = new TiXmlElement("员工");    sub->SetAttribute("ID" , "102");    sub->SetAttribute("职位" , "人事部经理");    child = new TiXmlElement("姓名");    content =new TiXmlText("黄蓉");    child->LinkEndChild(content);    sub->LinkEndChild(child);        root->LinkEndChild(sub);    doc.LinkEndChild(root);    doc.SaveFile("WriteTest.xml");                return 0;}

输出效果:

<?xml version="1.0" ?><!--群英集团人力资源表--><群英集团>    <员工 ID="011" 职位="技术总监">        <姓名>虚竹</姓名>    </员工>    <员工 ID="029" 职位="技术总监">        <姓名>乔峰</姓名>    </员工>    <员工 ID="100" 职位="总架构师">        <姓名>扫地僧</姓名>    </员工>    <员工 ID="101" 职位="公关部经理">        <姓名>韦小宝</姓名>    </员工>    <员工 ID="102" 职位="人事部经理">        <姓名>黄蓉</姓名>    </员工></群英集团>

注意:
在网上搜索如何用TinyXml时,本人普遍的发现了类似如下的代码

TiXmlDocument doc;TiXmlElement *ele = new TiXmlElement("test");doc.LinkEndChild(ele);doc.SaveFile("test.xml");

也就是只有new而没有delete。
于是当我第一次写的时候,就很守规矩的按部就班的在doc.SaveFile后面加上了delete ele,而这一加就把问题加出来了,程序直接在运行时崩掉了。
后来才知道,人家那样写是有原因的。当析构时,tinyxml会对所有已经连接进来的节点进行释放,所以不需要手动的去释放所new出来的东西,而如果TiXmlDocument对象也是new出来的,则需要对TiXmlDocument对象执行delete。

0 0
原创粉丝点击