【转】C++通过TinyXML类库读写XML

转自:http://blog.youkuaiyun.com/tennysonsky/article/details/48630005

原作者:Mike__Jiang


TinyXML是一个开源的解析XML的解析库,能够用于C++,能够在Windows或Linux中编译。这个解析库的模型通过解析XML文件,然后在内存中生成DOM模型,从而让我们很方便的遍历这棵XML树。


DOM模型即文档对象模型,是将整个文档分成多个元素(如书、章、节、段等),并利用树型结构表示这些元素之间的顺序关系以及嵌套包含关系。


使用之前,需要先下载TinyXML类库:http://download.youkuaiyun.com/detail/tennysonsky。也可在sourceforge上下载:http://sourceforge.net/projects/tinyxml/


然后解压缩TinyXML后,将这六个文件添加到你的c++工程中,分别是tinystr.h、tinystr.cpp、tinyxml.h、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.cpp。


如本示例中,只有 main.cpp 才是测试代码:



编写代码时,只需要包含 tinyxml.h 头文件即可,但是,编译时却需要把所有.cpp 文件都加上


示例代码如下:

  1. #include <stdio.h>  
  2. #include "tinyxml.h"  
  3. #include <iostream>  
  4. #include <cstring>  
  5. using namespace std;  
  6.   
  7. /* 
  8.     TiXmlDocument:文档类,它代表了整个xml文件 
  9.     TiXmlDeclaration:声明类,它表示文件的声明部分 
  10.     TiXmlComment:注释类,它表示文件的注释部分 
  11.     TiXmlElement:元素类,它是文件的主要部分,并且支持嵌套结构,一般使用这种结构来分类的存储信息,它可以包含属性类和文本类 
  12.     TiXmlAttribute/TiXmlAttributeSet:元素属性,它一般嵌套在元素中,用于记录此元素的一些属性 
  13.     TiXmlText:文本对象,它嵌套在某个元素内部 
  14. */  
  15. //创建xml文件  
  16. int writeXmlFile()  
  17. {  
  18.     TiXmlDocument *writeDoc = new TiXmlDocument; //xml文档指针  
  19.       
  20.     //文档格式声明  
  21.     TiXmlDeclaration *decl = new TiXmlDeclaration("1.0""UTF-8""yes");  
  22.     writeDoc->LinkEndChild(decl); //写入文档  
  23.   
  24.     int n = 3;  //父节点个数  
  25.   
  26.     TiXmlElement *RootElement = new TiXmlElement("Info");//根元素  
  27.     RootElement->SetAttribute("num", n); //属性  
  28.     writeDoc->LinkEndChild(RootElement);  
  29.       
  30.     for(int i=0; i<n; i++)//n个父节点  
  31.     {  
  32.         TiXmlElement *StuElement = new TiXmlElement("Stu");//Stu  
  33.         //设置属性  
  34.         StuElement->SetAttribute("class","A");  
  35.         if(2 == i)  
  36.         {  
  37.                 StuElement->SetAttribute("class","B");  
  38.         }  
  39.           
  40.         StuElement->SetAttribute("id",i+1);  
  41.         StuElement->SetAttribute("flag", (i+1)*10);  
  42.         RootElement->LinkEndChild(StuElement);//父节点写入文档  
  43.       
  44.         //姓名  
  45.         TiXmlElement *nameElement = new TiXmlElement("name");  
  46.         StuElement->LinkEndChild(nameElement);  
  47.   
  48.         TiXmlText *nameContent = new TiXmlText("mike");  
  49.         nameElement->LinkEndChild(nameContent);  
  50.           
  51.         //分数  
  52.         TiXmlElement *scoreElement = new TiXmlElement("score");  
  53.         StuElement->LinkEndChild(scoreElement);  
  54.   
  55.         TiXmlText *scoreContent = new TiXmlText("88");  
  56.         scoreElement->LinkEndChild(scoreContent);  
  57.           
  58.         //城市  
  59.         TiXmlElement *cityElement = new TiXmlElement("city");  
  60.         StuElement->LinkEndChild(cityElement);  
  61.   
  62.         TiXmlText *cityContent = new TiXmlText("Shenzhen");  
  63.         cityElement->LinkEndChild(cityContent);  
  64.           
  65.     }  
  66.       
  67.     writeDoc->SaveFile("stu_info.xml");  
  68.     delete writeDoc;  
  69.       
  70.     return 1;  
  71. }  
  72.   
  73. //解析xml文件  
  74. int readXmlFile()  
  75. {  
  76.     TiXmlDocument mydoc("stu_info.xml");//xml文档对象  
  77.     bool loadOk=mydoc.LoadFile();//加载文档  
  78.     if(!loadOk)  
  79.     {  
  80.         cout<<"could not load the test file.Error:"<<mydoc.ErrorDesc()<<endl;  
  81.         exit(1);  
  82.     }  
  83.   
  84.     TiXmlElement *RootElement=mydoc.RootElement();  //根元素, Info  
  85.     cout<< "[root name]" << RootElement->Value() <<"\n";  
  86.       
  87.     TiXmlElement *pEle=RootElement;  
  88.   
  89.     //遍历该结点  
  90.     for(TiXmlElement *StuElement = pEle->FirstChildElement();//第一个子元素  
  91.         StuElement != NULL;  
  92.         StuElement = StuElement->NextSiblingElement())//下一个兄弟元素  
  93.     {  
  94.         // StuElement->Value() 节点名称  
  95.         cout<< StuElement->Value() <<" ";  
  96.         TiXmlAttribute *pAttr=StuElement->FirstAttribute();//第一个属性  
  97.           
  98.         while( NULL != pAttr) //输出所有属性  
  99.         {  
  100.             cout<<pAttr->Name()<<":"<<pAttr->Value()<<" ";  
  101.             pAttr=pAttr->Next();  
  102.         }  
  103.         cout<<endl;  
  104.           
  105.         //输出子元素的值  
  106.         for(TiXmlElement *sonElement=StuElement->FirstChildElement();  
  107.         sonElement;  
  108.         sonElement=sonElement->NextSiblingElement())  
  109.         {  
  110.             cout<<sonElement->FirstChild()->Value()<<endl;  
  111.         }  
  112.     }  
  113.       
  114.     return 1;  
  115. }  
  116.   
  117. int main(int argc, char *argv[])  
  118. {  
  119.       
  120.     writeXmlFile();  
  121.     printf("\nafter write\n");  
  122.       
  123.     readXmlFile();  
  124.   
  125.     return 0;  
  126. }  
#include <stdio.h>
#include "tinyxml.h"
#include <iostream>
#include <cstring>
using namespace std;

/*
	TiXmlDocument:文档类,它代表了整个xml文件
	TiXmlDeclaration:声明类,它表示文件的声明部分
	TiXmlComment:注释类,它表示文件的注释部分
	TiXmlElement:元素类,它是文件的主要部分,并且支持嵌套结构,一般使用这种结构来分类的存储信息,它可以包含属性类和文本类
	TiXmlAttribute/TiXmlAttributeSet:元素属性,它一般嵌套在元素中,用于记录此元素的一些属性
	TiXmlText:文本对象,它嵌套在某个元素内部
*/
//创建xml文件
int writeXmlFile()
{
	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; i<n; i++)//n个父节点
	{
		TiXmlElement *StuElement = new TiXmlElement("Stu");//Stu
		//设置属性
		StuElement->SetAttribute("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;
	
	return 1;
}

//解析xml文件
int readXmlFile()
{
	TiXmlDocument mydoc("stu_info.xml");//xml文档对象
	bool loadOk=mydoc.LoadFile();//加载文档
	if(!loadOk)
	{
		cout<<"could not load the test file.Error:"<<mydoc.ErrorDesc()<<endl;
		exit(1);
	}

	TiXmlElement *RootElement=mydoc.RootElement();	//根元素, Info
	cout<< "[root name]" << RootElement->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<<pAttr->Name()<<":"<<pAttr->Value()<<" ";
			pAttr=pAttr->Next();
		}
		cout<<endl;
		
		//输出子元素的值
		for(TiXmlElement *sonElement=StuElement->FirstChildElement();
		sonElement;
		sonElement=sonElement->NextSiblingElement())
		{
			cout<<sonElement->FirstChild()->Value()<<endl;
		}
	}
	
	return 1;
}

int main(int argc, char *argv[])
{
	
	writeXmlFile();
	printf("\nafter write\n");
	
	readXmlFile();

	return 0;
}

编译运行结果如下:



生成的xml文件内容如下:

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>  
  2. <Info num="3">  
  3.     <Stu class="A" id="1" flag="10">  
  4.         <name>mike</name>  
  5.         <score>88</score>  
  6.         <city>Shenzhen</city>  
  7.     </Stu>  
  8.     <Stu class="A" id="2" flag="20">  
  9.         <name>mike</name>  
  10.         <score>88</score>  
  11.         <city>Shenzhen</city>  
  12.     </Stu>  
  13.     <Stu class="B" id="3" flag="30">  
  14.         <name>mike</name>  
  15.         <score>88</score>  
  16.         <city>Shenzhen</city>  
  17.     </Stu>  
  18. </Info>  
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Info num="3">
    <Stu class="A" id="1" flag="10">
        <name>mike</name>
        <score>88</score>
        <city>Shenzhen</city>
    </Stu>
    <Stu class="A" id="2" flag="20">
        <name>mike</name>
        <score>88</score>
        <city>Shenzhen</city>
    </Stu>
    <Stu class="B" id="3" flag="30">
        <name>mike</name>
        <score>88</score>
        <city>Shenzhen</city>
    </Stu>
</Info>

本教程示例代码下载请点此链接:http://download.youkuaiyun.com/detail/tennysonsky

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值