XML:
英文名称: extensible markup language;
下载地址:http://sourceforge.net/projects/tinyxml/
将6个文件拷贝到工程目录即可。
tinystr.h
tinyxml.h
tinystr.cpp
tinyxmlerror.cpp
tinyxmlparser.cpp
tinyxml.cpp
读取XML:
TiXmlElement *RootElement = NULL;
TiXmlDocument *pDoc = NULL;
string filefullPath ="test.xml";
pDoc = new TiXmlDocument(filefullPath.c_str());
pDoc->LoadFile();
RootElement = pDoc->RootElement();
使用RootElement即可遍历所有节点
遍历XML节点:
使用XML根节点即可遍历所有节点
TiXmlElement *currentNode = RootElement->FirstChildElement();
while (currentNode)
{
currentNode = currentNode->NextSiblingElement();
}
遍历XML节点的属性
TiXmlAttribute *Addr = currentNode->FirstAttribute();
while (Addr)
{
printf("%s %s\n",Addr->Name(),Addr->Value());//打印属性名字和对应值
Addr = Addr->Next();
}
生成XML:
pDoc = new TiXmlDocument();
TiXmlDeclaration *pDeclaration = new TiXmlDeclaration(("1.0"),("UTF-8"),(""));
pDoc->LinkEndChild(pDeclaration);
RootElement = new TiXmlElement(("MyGUI"));
RootElement->SetAttribute("type","Resource");
RootElement->SetAttribute("version","1.1");
pDoc->LinkEndChild(RootElement);
TiXmlElement *xnode = new TiXmlElement("Resource");
xnode->SetAttribute("type","ResourceSkin");
xnode->SetAttribute("name","pig");
RootElement->LinkEndChild(xnode);
//屏幕打印XML
pDoc->Print();
结果:
<?xml version="1.0" encoding="UTF-8" ?>
<MyGUI type="Resource" version="1.1">
</MyGUI>
//TiXmlElement *curNode
删除节点:
RootElement->RemoveChild(curNode);
添加节点:
RootElement->LinkEndChild(curNode);
pDoc->SaveFile("myxml.xml");