当前位置: 首页 > 工具软件 > pugixml > 使用案例 >

pugixml读写xml文件

孔征
2023-12-01

pugixml包含三个文件,分别为pugixml.cpp,pugixml.hpp,pugiconfig.hpp.(没有的话需自行下载),使用时将这三个文件添加到工程中,并包含相应的头文件。编译时一定要编译pugixml.cpp文件

实例代码

#include <iostream>
using namespace std;

#include "pugixml.hpp"
#include "pugiconfig.hpp"
using namespace pugi;




bool ReadXml(const string& fileName)
{
        xml_document doc;
        if (!doc.load_file(fileName.c_str())) { //加载xml文件
                cout << "load file faild";
                return false;
        }
        xml_node root = doc.child("root");  //根节点
        cout << "id:" << root.attribute("id").value() << endl;  //属性值

        xml_node node1 = root.child("node1");
        cout << "name:" << node1.attribute("name").value() << "  age:" <<
                node1.attribute("age").value() << "  weight:" << node1.attribute("weight").value() << endl;

        xml_node node2 = root.child("node2");

        for (auto node : node2.children()) {
                cout << "name:" << node.child("name").text().as_string() << endl;   //字符型
                cout << "age:" << node.child("age").text().as_int() << endl;        //整型
        }

        return true;
}

bool WriteXml(const string& fileName)
{
        xml_document doc;
        //xml声明部分
        xml_node declaration_node = doc.append_child(pugi::node_declaration);
        declaration_node.append_attribute("version") = "1.0";
        declaration_node.append_attribute("encoding") = "UTF-8";

        pugi::xml_node root = doc.append_child("root"); //根节点
        root.append_attribute("id") = "S1"; //根节点属性

        for (int i = 0; i < 3; ++i) {
                xml_node node = root.append_child("li");
                node.append_attribute("x") = i;
                node.append_attribute("y").set_value(i);
        }
        root.append_child("name").text().set("xiaohua");
        doc.save_file(fileName.c_str());

        return true;
}

int main()
{
        string readFileName = "read.xml";
        ReadXml(readFileName);
        string writeFileName = "write.xml";
        WriteXml(writeFileName);
        return 0;
}

read.xml

<?xml version="1.0" encoding="utf-8" ?>
<root id="s1">
        <node1 name="xiaohua" age="80" weight="34"/>
        <node2>
                <li>
                        <name>jj</name>
                        <age>20</age>
                </li>
                <li>
                        <name>hh</name>
                        <age>22</age>
                </li>
                <li>
                        <name>gg</name>
                        <age>23</age>
                </li>
        </node2>
</root>
~                                                                                                                                                
~         

write.xml

<?xml version="1.0" encoding="UTF-8"?>
<root id="S1">
        <li x="0" y="0" />
        <li x="1" y="1" />
        <li x="2" y="2" />
        <name>xiaohua</name>
</root>
 类似资料: