先说几句重点:
1,tinyxml 生成或解析XML非常好用
2,tinyxml 利用DOM(文档对象模型)操作XML,根节点与各个子节点相当于形成一棵树
3,只要你了解tinyxml的用法,可以只new对象而不用delete。
4,tinyxml包含6个文件 tinystr.cpp , tinystr.h , tinyxml.cpp , tinyxmlerror.cpp , tinyxml.h , tinyxmlparser.cpp
This inheritance list is sorted roughly, but not completely, alphabetically:
到了这里,直接上程序,只要你看完代码,就会处理最简单的XML文档了
#include #include"tinyxml.h"
intCreateXml()
{//创建一个XML结构
TiXmlDocument* pDoc = newTiXmlDocument();//创建一个根节点并连接到XML
TiXmlElement* pRoot = new TiXmlElement("item");
pDoc->LinkEndChild(pRoot);//创建一个name子节点并连接根节点下
TiXmlElement* nameElement = new TiXmlElement("name");
pRoot->LinkEndChild(nameElement);
nameElement->SetAttribute("ID","1");
TiXmlText* nameContent = new TiXmlText("opop");
nameElement->LinkEndChild(nameContent);
TiXmlElement* addrElement = new TiXmlElement("addr");
pRoot->LinkEndChild(addrElement);
TiXmlText* addrContent = new TiXmlText("guangzhou");
addrElement->LinkEndChild(addrContent);
TiXmlElement* telElement = new TiXmlElement("tel");
pRoot->LinkEndChild(telElement);
TiXmlText* telContent = new TiXmlText("1341532545");
telElement->LinkEndChild(telContent);
TiXmlElement* emailElement = new TiXmlElement("email");
pRoot->LinkEndChild(emailElement);
TiXmlText* emailContent = new TiXmlText("opop@qq.com");
emailElement->LinkEndChild(emailContent);//保存到文件
pDoc->SaveFile("test.xml");deletepDoc; //应该是必要的return 0;
}intReadXml()
{//创建一个XML结构并载入文件内容
TiXmlDocument* pDoc = newTiXmlDocument();
pDoc->LoadFile("test.xml");
pDoc->Print();//获取根节点
TiXmlElement* pRoot = pDoc->RootElement();
printf("%s\n",pRoot->Value());//获取根节点下的子节点并打印其内容
TiXmlElement* pChild = pRoot->FirstChildElement("name");
printf("%s\n",pChild->FirstChild()->ToText()->Value());
pChild= pRoot->FirstChildElement("addr");
printf("%s\n",pChild->FirstChild()->ToText()->Value());
pChild= pRoot->FirstChildElement("tel");
printf("%s\n",pChild->FirstChild()->ToText()->Value());
pChild= pRoot->FirstChildElement("email");
printf("%s\n",pChild->FirstChild()->ToText()->Value());deletepDoc;//应该是必要的
}intmain() { CreateXml(); ReadXml();return 0; }
好了,见证奇迹吧
最后再说一个重点:关于delete的问题
代码里面很清楚,有delete,但是这个例子的delete是必须的,不然就内存泄露了。
但是注意delete的对象只有一个,其他new的对象如果delete就出问题了,原因后面会讲到
怎样完全不用delete呢?很简单!!!
请看下面一段官方代码:只有new,没有delete
voidwrite_simple_doc2( )
{//same as write_simple_doc1 but add each node//as early as possible into the tree.
TiXmlDocument doc;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "");
doc.LinkEndChild( decl );
TiXmlElement* element = new TiXmlElement( "Hello");
doc.LinkEndChild( element );
TiXmlText* text = new TiXmlText( "World");
element->LinkEndChild( text );
doc.SaveFile("madeByHand2.xml");
}
Both of these produce the XML:
World
对比完应该就发现了,只要代码中TiXmlDocument 对象不要在堆中new,直接在栈中生成,那么,就不需要任何delete操作,而且必须不能delete,否则程序就崩了。
原因很简单,只要TiXmlDocument 对象这个基本结构被销毁了,所有的节点会被自动销毁。TinyXML保证不坑你