为了账号安全,请及时绑定邮箱和手机立即绑定

tinyxml 库

标签:
C++

C++读取xml配置文件 - tinyxml2

tinyxml基本结构


xml文件示例

animals.xml<?xml version="1.0" encoding="UTF-8"?><!-- Feldman Family Circus Animals --><animalList>
    <animal>
        <name>Herby</name>
        <species>elephant</species>
        <dateOfBirth>1992-04-23</dateOfBirth>
        <veterinarian name="Dr. Hal Brown" phone="(801)595-9627" />
        <trainer name="Bob Fisk" phone="(801)881-2260"/>
    </animal></animalList>

类结构

webp

Tinyxml类结构

  • 1, TiXmlBase 为所有类型的基类, 提供基本的打印功能和部分工具函数;

  • 2, TiXmlNode 为所有节点的父类;

    • 2.1 TiXmlComment 对应 xml 中的注释, 即 ``;

    • 2.2 TiXmlDeclaration 对应 xml 中的文档属性, 即 <?xml version="1.0" encoding="UTF-8"?>

    • 2.3 TiXmlDocument 为容器类,指代 animals.xml 文档本身;

    • 2.4 TiXmlElement 为xml元素, 可以嵌套, 如 <animal> </animal> 为 xml 元素,可以继续嵌套 <name> <species>... 等元素;

    • 2.5 TiXmlText 指代 xml 元素的 val, 同 TiXmlAttribute 基本只在生成文档时使用.

    • 2.6 指代 xml 文档中不能正常解析的部分.

  • 3, TiXmlAttribute 对应 xml 中的属性,即 <veterinarian name="Dr. Hal Brown" phone="(801)595-9627" /> name 和 phone 属性,在生成 xml 文档时用到,读取时没有用到.

demo

#include "tinyxml.h"#include <iostream>int main(){    using namespace std;    TiXmlDocument docAnml("animals.xml");
    docAnml.LoadFile();
    TiXmlNode* dec = docAnml.FirstChild();    cout << "xml declaration: "<<dec->Value() << endl;    // 输出 xml declaration: , 没有 declaration 的内容
    dec = dec->NextSibling();    cout << "xml comment: "<<dec->Value() << endl;    //  xml declaration:  Feldman Family Circus Animals

    TiXmlElement* root = docAnml.RootElement();    cout << "root element is " << root->Value() << endl;    // root element is animalList
    TiXmlElement* animal = root->FirstChildElement(); // animal
    TiXmlElement* name   = animal->FirstChildElement(); // name
    cout << "name is : " << name->FirstChild()->Value() << endl;
    name = name->NextSiblingElement(); // species
    name = name->NextSiblingElement(); // date - of - birth
    TiXmlElement* Vet = name->NextSiblingElement(); // veterinarian
    cout << "attribute name : " << Vet->Attribute("name") << endl;    // ttribute name : Dr. Hal Brown}// g++ -o demo_tixml demo_tixml.cpp -I./inc -L./lib -ltinyxml -DTIXML_USE_STL



作者:呆呆的张先生
链接:https://www.jianshu.com/p/fd4228b9c444


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消