C++ tinyxml的封装与使用

1.tinyxml简介

TinyXml是一个基于DOM模型的、非验证的轻量级C++解释器。
下载地址:https://sourceforge.net/projects/tinyxml/
我下载的是tinyxml_2_6_2.zip,解压出来如下图:

tinyxml

将这里面的所有.h和.cpp复制到你的工程下就可以了,不需要链接库。

2.代码

2.1 需要解析的xml

<?xml version="1.0" encoding="UTF-8"?>  
<phonebook>  
    <!--one item behalfs one contacted person.-->  
    <item>  
        <name>xiaoming</name>  
    <addr>chengdu</addr>  
    <tel>15884470211</tel>  
    <email>[email protected]</email>  
    </item>  
    <item>  
        <name>xiaohua</name>  
    <addr>beijing</addr>  
    <tel>15840330481</tel>  
    <email>[email protected]</email>  
    </item>  
    <!--more contacted persons.-->  
</phonebook> 

2.2 myxml.h头文件

#ifndef _MYXML_H_
#define _MYXML_H_
#include "tinyxml/tinyxml.h"
#include <iostream>
#include <string>
using namespace std;
class ParserXml{
public:
    ParserXml(const string& filename);
    bool Parser();
private:
    TiXmlDocument doc;
};
#endif //_MYXML_H_

2.3 myxml.cpp实现文件

#include "myxml.h"

ParserXml::ParserXml(const string& filename){
    doc = filename.c_str();
}

bool ParserXml::Parser(){
    bool loadOkay = doc.LoadFile();
    if(!loadOkay){
        cout<<"load xml file error"<<endl;
        return false;
    }
    TiXmlElement* root = doc.RootElement();
    cout<<"-------contact person info-------"<<endl;
    for(TiXmlNode* item= root->FirstChild("item");item;
        item = item->NextSibling("item")){
            TiXmlNode* child = item->FirstChild();
            const char* name = child->ToElement()->GetText();  
            if(name){
                cout<<"name:"<<name<<endl;
            }

            child = item->IterateChildren(child);  
            const char* addr = child->ToElement()->GetText();  
            if (addr) {  
                cout<<"addr:"<<addr<<endl;
            }

            child = item->IterateChildren(child);  
            const char* tel = child->ToElement()->GetText();  
            if (tel)
                cout<<"tel:"<<tel<<endl;

            child = item->IterateChildren(child);  
            const char* email = child->ToElement()->GetText();  
            if(email)
                cout<<"email:"<<email<<endl;


        }
    return true;
}

2.4 test.cpp

#include "tinyxml/tinyxml.h"
#include <iostream>
#include "myxml.h"
using namespace std;
int main(){
    string filePath = "test.xml";
    ParserXml pxml(filePath);
    bool okflag = pxml.Parser();
    if(!okflag)
        return -1;
    return 0;
}

3输出

输出结果如下图:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_28712713/article/details/77850664
今日推荐