C++建立 XML 文件方法
1. 通过 fprintf 函数写 xml 文件,添加: #include
string FilePathxml("xxxxx");
FILE *fp;
char fname[200];
strcpy(fname,FilePathxml.c_str());
fp=fopen(fname,"w+");
fprintf(fp,"%s","");
fprintf(fp,"\n%s","");
fprintf(fp,"\n%s","<我¨°是º?最Á?帅¡ì的Ì?>");
fprintf(fp,"\n%s","");
fclose(fp);
2. 通过 TinyXML 类库读写 XML 文件
TinyXML 是一个开源的解析 XML 的解析库,能够用于 C++,能够在 Windows 或 Linux 中编译。这
个解析库的模型通过解析 XML 文件,然后在内存中生成 DOM 模型,从而让我们很方便的遍历这
棵 XML 树。DOM 模型即文档对象模型,是将整个文档分成多个元素(如书、章、节、段等),并
利用树型结构表示这些元素之间的顺序关系以及嵌套包含关系。
http://blog.csdn.net/tennysonsky/article/details/48630005。
用之前,需要先下载 TinyXML 类库:http://download.csdn.net/detail/tennysonsky。也可
在 sourceforge 上下载:http://sourceforge.net/projects/tinyxml/。
1.然后解压缩 TinyXML 后,使用本文再稍加工(在每个文件添加:#include “stdafx.h”)的
六个文件,这六个文件添加到你的 c++工程中,分别是: tinystr.h、 tinystr.cpp、 tinyxml.h、
tinyxml.cpp、 tinyxmlerror.cpp、tinyxmlparser.cpp。
2.编写代码时,只需要包含 tinyxml.h 头文件即可,但是,编译时却需要把所有.cpp 文件都
加上:
3. 在解决方案资源管理器上添加 6 个文件:
写 xml 文件:
TiXmlDocument *writeDoc = new TiXmlDocument; //xml 文档指针
//文档格式声明
TiXmlDeclaration *decl = new TiXmlDeclaration("1.0", "UTF-8", "yes");
writeDoc->LinkEndChild(decl); //写入文档
int n = 3;
//父节点个数
TiXmlElement *RootElement = new TiXmlElement("Info");//根元素
RootElement->SetAttribute("num", n); //属性
writeDoc->LinkEndChild(RootElement);
{
for(int i=0; iSetAttribute("class","A");
if(2 == i)
{
}
StuElement->SetAttribute("class","B");
StuElement->SetAttribute("id",i+1);
StuElement->SetAttribute("flag", (i+1)*10);
RootElement->LinkEndChild(StuElement);//父节点写入文档
//姓名
TiXmlElement *nameElement = new TiXmlElement("name");
StuElement->LinkEndChild(nameElement);
TiXmlText *nameContent = new TiXmlText("mike");
nameElement->LinkEndChild(nameContent);
//分数
TiXmlElement *scoreElement = new TiXmlElement("score");
StuElement->LinkEndChild(scoreElement);
TiXmlText *scoreContent = new TiXmlText("88");
scoreElement->LinkEndChild(scoreContent);
//城市
TiXmlElement *cityElement = new TiXmlElement("city");
StuElement->LinkEndChild(cityElement);
TiXmlText *cityContent = new TiXmlText("Shenzhen");
cityElement->LinkEndChild(cityContent);
}
writeDoc->SaveFile("stu_info.xml");
delete writeDoc;
读 XML 文件:
TiXmlDocument mydoc("stu_info.xml");//xml 文档对象
bool loadOk=mydoc.LoadFile();//加载文档
if(!loadOk)
{
cout<<"could not load the test
file.Error:"<
Value() <<"\n";
TiXmlElement *pEle=RootElement;
//遍历该结点
for(TiXmlElement *StuElement = pEle->FirstChildElement();//第一个子元素
StuElement != NULL;
StuElement = StuElement->NextSiblingElement())//下一个兄弟元素
// StuElement->Value() 节点名称
cout<< StuElement->Value() <<" ";
TiXmlAttribute *pAttr=StuElement->FirstAttribute();//第一个属性
while( NULL != pAttr) //输出所有属性
{
}
cout<Name()<<":"<Value()<<" ";
pAttr=pAttr->Next();
cout<FirstChildElement();
sonElement;
sonElement=sonElement->NextSiblingElement())
{
}
cout<FirstChild()->Value()<读取结果见下图: