温馨提示×

C++中怎么读取XML文件

c++
小亿
190
2024-04-16 09:45:11
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中读取XML文件通常使用第三方库来实现,比较常用的库有TinyXML、RapidXML和PugiXML等。

以下是使用PugiXML库来读取XML文件的示例代码:

#include <iostream>
#include "pugixml.hpp"

int main() {
    pugi::xml_document doc;
    
    if (!doc.load_file("example.xml")) {
        std::cerr << "Failed to load XML file." << std::endl;
        return 1;
    }
    
    pugi::xml_node root = doc.child("root");
    
    for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling()) {
        std::cout << "Node name: " << node.name() << std::endl;
        
        for (pugi::xml_attribute attr = node.first_attribute(); attr; attr = attr.next_attribute()) {
            std::cout << "Attribute name: " << attr.name() << ", value: " << attr.value() << std::endl;
        }
        
        std::cout << "Node value: " << node.child_value() << std::endl;
    }
    
    return 0;
}

在上面的代码中,我们首先加载XML文件(假设文件名为"example.xml"),然后获取根节点,遍历根节点的子节点,并输出节点的名称、属性和值。

请注意,你需要在项目中安装PugiXML库,并且在编译时链接该库。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++中xml文件如何读取和保存

0