c++

C++中怎么读取XML文件

小亿
91
2024-04-16 09:45:11
栏目: 编程语言

在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库,并且在编译时链接该库。

0
看了该问题的人还看了