0
点赞
收藏
分享

微信扫一扫

【C++】开源:tinyxml2解析库配置使用

扶摇_hyber 2023-08-08 阅读 60

文章目录

😏1. 项目介绍

项目Github地址:https://github.com/leethomason/tinyxml2

TinyXML-2是一个轻量级的C++库,用于解析和生成XML文档。它是对原始TinyXML库的改进和扩展,提供了更快速、更强大的XML处理功能。

以下是一些TinyXML-2的主要特点和功能:

😊2. 环境配置

下面进行环境配置:

sudo apt-get install build-essential
git clone https://github.com/leethomason/tinyxml2.git
cd tinyxml2
make
sudo make install
# 查看版本
pkg-config --modversion tinyxml2

g++编译:g++ -o main main.cpp -ltinyxml2

😆3. 使用说明

下面进行使用分析:

一个示例:

#include <iostream>
#include <tinyxml2.h>

int main() {
    // 创建一个XML文档对象
    tinyxml2::XMLDocument doc;

    // 加载XML文件
    if (doc.LoadFile("example.xml") == tinyxml2::XML_SUCCESS) {
        // 打印根元素名称
        tinyxml2::XMLElement* root = doc.FirstChildElement("Root");
        if (root) {
            std::cout << "Root Element: " << root->Name() << std::endl;
        }

        // 遍历并打印所有子元素
        tinyxml2::XMLElement* element = root->FirstChildElement();
        while (element) {
            std::cout << "Element Name: " << element->Name() << std::endl;

            // 获取元素的属性值
            const char* attributeValue = element->Attribute("attribute");
            if (attributeValue) {
                std::cout << "Attribute Value: " << attributeValue << std::endl;
            }

            // 获取元素的文本内容
            const char* textValue = element->GetText();
            if (textValue) {
                std::cout << "Text Value: " << textValue << std::endl;
            }

            element = element->NextSiblingElement();
        }
    }

    // 创建一个新的XML文档
    tinyxml2::XMLDocument newDoc;
    
    // 创建根元素
    tinyxml2::XMLElement* newRoot = newDoc.NewElement("NewRoot");
    newDoc.InsertFirstChild(newRoot);

    // 创建子元素
    tinyxml2::XMLElement* newElement = newDoc.NewElement("NewElement");
    newRoot->InsertEndChild(newElement);

    // 设置属性值
    newElement->SetAttribute("attribute", "value");

    // 设置文本内容
    newElement->SetText("Hello, World!");

    // 保存XML文件
    newDoc.SaveFile("new_example.xml");

    return 0;
}

在这里插入图片描述

以上。

举报

相关推荐

0 条评论