使用tinyxml2库解析xml

tinyxml2简介

tinyxml2是c++编写的轻量级的xml解析器,而且是开放源代码的,在一些开源的游戏引擎中用的比较多。源码托管在github上。
源码地址:https://github.com/leethomason/tinyxml2

这里写图片描述

tinyxml2使用起来非常简单,下载源码后无需编译成lib文件,直接將tinyxml2.h和tinyxml2.cpp两个文件添加到你自己的工程中即可。

tinyxml2使用

我们现在有一个persons.xml文件,里面存放着一些人员信息,内容如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <persons>
        <person name="张三">
            <sex></sex>
            <age>30</age>
        </person>
        <person name="花花">
            <sex></sex>
            <age>20</age>
        </person>   
    </persons>

现在我们使用tinyxml2库遍历该xml文件,获取姓名为”花花“的人员的全部信息。

代码如下:

#include "stdafx.h"
#include <string>
#include <iostream>
#include "tinyxml2.h"
#define String std::string
using namespace tinyxml2;
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    /*
    <?xml version="1.0" encoding="UTF-8"?>
    <persons>
        <person name="张三">
            <sex>男</sex>
            <age>30</age>
        </person>
        <person name="花花">
            <sex>女</sex>
            <age>20</age>
        </person>   
    </persons>
    */
    //通过遍历输出姓名为“花花”的个人信息
    XMLDocument* doc = new XMLDocument();  
    if(doc->LoadFile("persons.xml") != XML_NO_ERROR)
    {
        cout<<"read file error!"<<endl;
        return -1;
    }
    //获取根节点,即persons节点
    XMLElement* root = doc->RootElement();  
    XMLElement* person = root->FirstChildElement("person");  
    while (person)  
    {  
         //获取person的name属性
         const XMLAttribute * nameAttr = person->FirstAttribute();
         String perName = nameAttr->Value();
         if(perName == "花花")
         {
             cout<<nameAttr->Name()<<":"<<nameAttr->Value()<<endl;
             //遍历person的其他子节点
             XMLElement * perAttr = person->FirstChildElement();
             while(perAttr)
             {
                 cout<<perAttr->Name()<<":"<<perAttr->GetText()<<endl;
                 perAttr = perAttr->NextSiblingElement();
             }
         }
         person =  person->NextSiblingElement();
    }  
    delete doc;
    system("pause");
}

tinyxml2采用DOM(文档对象模型)方式处理xml文件,xml文件中的每一种元素都有对应的类。

doc->LoadFile("persons.xml")

XMLDocument类的对象代表一份xml文档实例,调用LoadFile方法与xml文件绑定。

XMLElement* root = doc->RootElement();  
XMLElement* person = root->FirstChildElement("person"); 

我们通过XMLDocument类的RootElement获取根节点(xml文件的根节点只有一个),通过root->FirstChildElement(“person”)获取元素名为person的第一个子节点。有了该节点调用XMLElement类NextSiblingElement()方法不断循环遍历即可。

运行效果

这里写图片描述

可以看到我们需要的信息打印了出来。

原文地址:https://www.cnblogs.com/lanzhi/p/6468956.html