最近老师要求的一个项目中需要在C++对XML文件进行解析,原来只在JAVA中做过类似的解析,然后上了某度了一下,最后搜了一篇关于TinyXML的博客,地址如下:http://blog.csdn.net/mhapdream/article/details/9088363

感觉TinyXML比较好用,准备用它来解析.

TinyXML下载地址:http://sourceforge.net/projects/tinyxml/

下载下来后,只需要将tinyxml.h、tinystr.h、tinystr.cpp、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.cpp这五文件导入工程即可.

下面举两个例,这两个例子基本囊括XML的一些操作:

#include <iostream>
#include "tinyxml.h"
#include "tinystr.h"
#include <string>
#include <windows.h>
#include <atlstr.h>
using namespace std;CString GetAppPath()
{//获取应用程序根目录TCHAR modulePath[MAX_PATH];GetModuleFileName(NULL, modulePath, MAX_PATH);CString strModulePath(modulePath);strModulePath = strModulePath.Left(strModulePath.ReverseFind(_T('\\')));return strModulePath;
}bool CreateXmlFile(string& szFileName)
{//创建xml文件,szFilePath为文件保存的路径,若创建成功返回true,否则falsetry{//创建一个XML的文档对象。TiXmlDocument *myDocument = new TiXmlDocument();//创建一个根元素并连接。TiXmlElement *RootElement = new TiXmlElement("Persons");myDocument->LinkEndChild(RootElement);//创建一个Person元素并连接。TiXmlElement *PersonElement = new TiXmlElement("Person");RootElement->LinkEndChild(PersonElement);//设置Person元素的属性。PersonElement->SetAttribute("ID", "1");//创建name元素、age元素并连接。TiXmlElement *NameElement = new TiXmlElement("name");TiXmlElement *AgeElement = new TiXmlElement("age");PersonElement->LinkEndChild(NameElement);PersonElement->LinkEndChild(AgeElement);//设置name元素和age元素的内容并连接。TiXmlText *NameContent = new TiXmlText("周星星");TiXmlText *AgeContent = new TiXmlText("22");NameElement->LinkEndChild(NameContent);AgeElement->LinkEndChild(AgeContent);CString appPath = GetAppPath();string seperator = "\\";string fullPath = appPath.GetBuffer(0) +seperator+szFileName;myDocument->SaveFile(fullPath.c_str());//保存到文件}catch (string& e){return false;}return true;
}bool ReadXmlFile(string& szFileName)
{//读取Xml文件,并遍历try{CString appPath = GetAppPath();string seperator = "\\";string fullPath = appPath.GetBuffer(0) +seperator+szFileName;//创建一个XML的文档对象。TiXmlDocument *myDocument = new TiXmlDocument(fullPath.c_str());myDocument->LoadFile();//获得根元素,即Persons。TiXmlElement *RootElement = myDocument->RootElement();//输出根元素名称,即输出Persons。cout << RootElement->Value() << endl;//获得第一个Person节点。TiXmlElement *FirstPerson = RootElement->FirstChildElement();//获得第一个Person的name节点和age节点和ID属性。TiXmlElement *NameElement = FirstPerson->FirstChildElement();TiXmlElement *AgeElement = NameElement->NextSiblingElement();TiXmlAttribute *IDAttribute = FirstPerson->FirstAttribute();//输出第一个Person的name内容,即周星星;age内容,即;ID属性,即。cout << NameElement->FirstChild()->Value() << endl;cout << AgeElement->FirstChild()->Value() << endl;cout << IDAttribute->Value()<< endl;}catch (string& e){return false;}return true;
}
int main()
{string fileName = "info.xml";CreateXmlFile(fileName);ReadXmlFile(fileName);
}

生成的XML文件如下:

运行结果如下:

第二个例子比较全面:

#include <string>
#include <list>
#include <map>
#include "tinyxml.h"using namespace std;typedef std::map<std::string,std::string> MessageMap;// a basic window abstraction - demo purposes only
class WindowSettings
{
public:int x,y,w,h;string name;WindowSettings(): x(0), y(0), w(100), h(100), name("Untitled"){}WindowSettings(int x, int y, int w, int h, const string& name){this->x=x;this->y=y;this->w=w;this->h=h;this->name=name;}
};class ConnectionSettings
{
public:string ip;double timeout;
};class AppSettings
{
public:string m_name;MessageMap m_messages;list<WindowSettings> m_windows;ConnectionSettings m_connection;AppSettings() {}void save(const char* pFilename);void load(const char* pFilename);// just to show how to do itvoid setDemoValues(){m_name="MyApp";m_messages.clear();m_messages["Welcome"]="Welcome to "+m_name;m_messages["Farewell"]="Thank you for using "+m_name;m_windows.clear();m_windows.push_back(WindowSettings(15,15,400,250,"Main"));m_connection.ip="Unknown";m_connection.timeout=123.456;}
};void AppSettings::save(const char* pFilename)
{TiXmlDocument doc;  TiXmlElement* msg;TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );  doc.LinkEndChild( decl );  TiXmlElement * root = new TiXmlElement( this->m_name.c_str() );  doc.LinkEndChild( root );  TiXmlComment * comment = new TiXmlComment();comment->SetValue(" Settings for MyApp " );  root->LinkEndChild( comment );  TiXmlElement * msgs = new TiXmlElement( "Messages" );  root->LinkEndChild( msgs );  msg = new TiXmlElement( "Welcome" );  msg->LinkEndChild( new TiXmlText( this->m_messages["Welcome"].c_str() ));  msgs->LinkEndChild( msg );  msg = new TiXmlElement( "Farewell" );  msg->LinkEndChild( new TiXmlText( this->m_messages["Farewell"].c_str() ));  msgs->LinkEndChild( msg );  TiXmlElement * windows = new TiXmlElement( "Windows" );  root->LinkEndChild( windows );  for(list<WindowSettings>::iterator iter = m_windows.begin(); iter != m_windows.end(); iter++){TiXmlElement * window;window = new TiXmlElement( "Window" );  windows->LinkEndChild( window );  window->SetAttribute("name", iter->name.c_str());window->SetAttribute("x", iter->x);window->SetAttribute("y", iter->y);window->SetAttribute("w", iter->w);window->SetAttribute("h", iter->h);}TiXmlElement * cxn = new TiXmlElement( "Connection" );  root->LinkEndChild( cxn );  cxn->SetAttribute("ip", m_connection.ip.c_str());cxn->SetDoubleAttribute("timeout", m_connection.timeout); // floating point attribdoc.SaveFile(pFilename);
}
void AppSettings::load(const char* pFilename)
{TiXmlDocument doc(pFilename);if (!doc.LoadFile()) return;TiXmlHandle hDoc(&doc);TiXmlElement* pElem;TiXmlHandle hRoot(0);// block: name{pElem=hDoc.FirstChildElement().Element();// should always have a valid root but handle gracefully if it doesif (!pElem) return;m_name=pElem->Value();// save this for laterhRoot=TiXmlHandle(pElem);}// block: string table{m_messages.clear(); // trash existing tablepElem=hRoot.FirstChild( "Messages" ).FirstChild().Element();for( pElem; pElem; pElem=pElem->NextSiblingElement()){const char *pKey=pElem->Value();const char *pText=pElem->GetText();if (pKey && pText) {m_messages[pKey]=pText;}}}// block: windows{m_windows.clear(); // trash existing listTiXmlElement* pWindowNode=hRoot.FirstChild( "Windows" ).FirstChild().Element();for( pWindowNode; pWindowNode; pWindowNode=pWindowNode->NextSiblingElement()){WindowSettings w;const char *pName=pWindowNode->Attribute("name");if (pName) w.name=pName;pWindowNode->QueryIntAttribute("x", &w.x); // If this fails, original value is left as-ispWindowNode->QueryIntAttribute("y", &w.y);pWindowNode->QueryIntAttribute("w", &w.w);pWindowNode->QueryIntAttribute("hh", &w.h);m_windows.push_back(w);}}// block: connection{pElem=hRoot.FirstChild("Connection").Element();if (pElem){m_connection.ip=pElem->Attribute("ip");pElem->QueryDoubleAttribute("timeout",&m_connection.timeout);}}
}
int main(void)
{// block: customise and save settings{AppSettings settings;settings.m_name="HitchHikerApp";settings.m_messages["Welcome"]="Don't Panic";settings.m_messages["Farewell"]="Thanks for all the fish";settings.m_windows.push_back(WindowSettings(15,25,300,250,"BookFrame"));settings.m_windows.push_back(WindowSettings(5,5,350,50,"BookFrame2"));settings.m_connection.ip="192.168.0.77";settings.m_connection.timeout=42.0;settings.save("appsettings2.xml");}// block: load settings{AppSettings settings;settings.load("appsettings2.xml");printf("%s: %s\n", settings.m_name.c_str(), settings.m_messages["Welcome"].c_str());for(list<WindowSettings>::iterator iter = settings.m_windows.begin(); iter != settings.m_windows.end(); iter++){printf("%s: Show window '%s' at %d,%d (%d x %d)\n", settings.m_name.c_str(), iter->name.c_str(), iter->x, iter->y, iter->w, iter->h);}printf("%s: %s\n", settings.m_name.c_str(), settings.m_messages["Farewell"].c_str());}return 0;
}

生成的XML文件如下:

运行结果如下:

C++中用TinyXML对XML文件进行解析相关推荐

  1. mybatis中config.xml文件的解析

    config.xml文件的解析是主要是XMLConfigBuilder完成的,通过调用parseConfiguration来实现整个解析过程 public Configuration parse() ...

  2. IOS开发基础之使用AFNetworking框架实现xml文件的解析

    IOS开发基础之使用AFNetworking框架实现xml文件的解析 info.plist加入这行代码 <key>NSAppTransportSecurity</key> &l ...

  3. 使用c#对xml文件进行解析 功能演示 161483724

    使用c#对xml文件进行解析 功能演示 161483724 导入命名空间 实例化一个节点文档对象 读取文件 获取根节点 获取节点的名称 获取所有子节点 类对象数组的对象 根据索引从节点集合中取出节点对 ...

  4. (C++)将数据库文件导出XML文件以及解析XML文件生成数据库文件的处理方法

    将数据库文件导出XML文件以及解析XML文件生成数据库文件的处理方法 思路:将数据库所有要导出的信息通过sql语句得到,存储到结构体中,然后将结构体的内容通过自定义的xml格式导出. 此方法使用的是T ...

  5. python读取xml文件信息_python读取xml文件方法解析

    关于python读取xml文章很多,但大多文章都是贴一个xml文件,然后再贴个处理文件的代码.这样并不利于初学者的学习,希望这篇文章可以更通俗易懂的教如何使用python来读取xml文件. 什么是xm ...

  6. tinyXml生成XML文件

    1.tinyXMl生成XML文件 #include <stdio.h> #include <string> using namespace std;#include " ...

  7. 【C++】TinyXML读取xml文件用法详解

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 前言 XML文件理解 常用的XML类方法使用 总结 前言 TinyXML下载地址:https://sourceforge.n ...

  8. tinyxml 读取文本节点_【C++】【TinyXml】xml文件的读写功能使用——写xml文件

    TinyXml工具是常用比较简单的C++中xml读写的工具 需要加载 #include "TinyXml\tinyxml.h" 在TinyXML中,根据XML的各种元素来定义了一些 ...

  9. android xml解析demo,Android解析自定义xml文件--Sax解析xml文件,测试demo(方案二)...

    转载请注明出处:http://blog.csdn.net/droyon/article/details/9346657 Sax解析xml 以下是测试Demo 运行程序类 public class Te ...

最新文章

  1. 用 Python 对比两个目录下的内容,并生成 Json 文件
  2. linux 硬软链接区别
  3. MediatR 知多少
  4. idea maven创建java项目_新版本IntelliJ IDEA 构建maven,并用Maven创建一个web项目(图文教程)...
  5. 求余运算转换为位运算
  6. 蔚来汽车回应“十四万元补胎”纠纷:车主未及时报案 除轮胎外底盘也严重受损...
  7. 【转】将QT开发的界面程序封装成DLL,在VC中成功调用
  8. Yandex.Algorithm 2011 Round 2 D. Powerful array 莫队算法
  9. 从DLL导出.a文件
  10. ora-30926:无法在源表中获得一组稳定的行
  11. Excel 横向比例图
  12. 计算机bios设置系统安装教程,U盘装系统BIOS设置教程进行设置图文教程
  13. UI设计师必备|Web设计尺寸规范
  14. 2019目标,做个精力充沛的人,身体工作双丰收
  15. 钢条切割(记忆型递归)dp
  16. 三层交换机与路由器对接上网配置示例
  17. 朱慕慕:ui设计包括什么内容,ui设计包括有几部分内容?
  18. pandas取第一行数据_Pandas DataFrame 取一行数据会得到Series的方法
  19. 一个90后博士眼中香港房奴梦:不吃不喝大干20年
  20. Python自动化生成代码以及验证代码汇总

热门文章

  1. C++标准转换运算符:static_cast
  2. addressof表达式不能转换为long_2.3 C++赋值运算符与表达式 | 将有符号数据赋给无符号...
  3. [洛谷P3346][ZJOI2015]诸神眷顾的幻想乡
  4. Oracle 12C R2-新特性-PDB的磁盘I/O(IOPS,MBPS)资源管理
  5. Linux下Nginx+Tomcat整合的安装与配置
  6. 拿什么拯救你,程序新丁?
  7. OSPF:STUB与NSSA区别
  8. tmp name php,linux环境 上传文件失败 tmp_name为空
  9. html5 PHP 分片上传,H5分片上传含前端JS和后端处理(thinkphp)
  10. 数值范围_量比指标怎么看?量比数值的意义