项目中建议(要求)使用pugi解析xml,那么今天就来学习一下pugi。

    下载
    下载网址:https://pugixml.org

    使用方式:
    官网介绍第一句称自己为轻量化、简单、快速的c++下xml解析工具,实际使用上手难度确实低。
    将src内的pugiconfig.hpp、pugixml.cpp、pugixml.hpp放入工程中,就可以使用了,就是这么简单。

    简单示例:pugi解析xml简单字符串
    这是一个超简单示例:

    1. #include <iostream>
    2. #include "pugiconfig.hpp"
    3. #include "pugixml.hpp"
    4. #include <string>
    5. using namespace std;
    6. int main()
    7. {
    8. char xmlStr[1024] = "<?xml version=\"1.0\"?>\r\n"
    9. "<Response>\r\n"
    10. "<CmdType>DeviceInfo</CmdType>\r\n"
    11. "<SN>17430</SN>\r\n"
    12. "<DeviceID>102934857689237</DeviceID>\r\n"
    13. "<Manufacturer>Happtimesoft</Manufacturer>\r\n"
    14. "<Model>HTIPC</Model>\r\n"
    15. "</Response>\r\n";
    16. pugi::xml_document doc;
    17. doc.load_string(xmlStr);
    18. pugi::xml_node response = doc.child("Response");
    19. //遍历
    20. for (pugi::xml_node node = response.first_child(); node != nullptr; node = node.next_sibling())
    21. {
    22. //cout << node.child_value() << endl; //两种访问方式
    23. cout << node.name() << ": " << node.text().as_string() << endl;
    24. }
    25. //特定访问
    26. pugi::xml_node sn = response.child("SN");
    27. cout << "SN: " << sn.child_value() << endl;
    28. system("pause");
    29. return 0;
    30. }

    简单示例:pugi解析简单xml文件
    xml文件内容:

    1. <?xml version="1.0"?>
    2. <Response>
    3. <CmdType>DeviceInfo</CmdType>
    4. <SN>17430</SN>
    5. <DeviceID>102934857689237</DeviceID>
    6. <Manufacturer>Happtimesoft</Manufacturer>
    7. <Model>HTIPC</Model>
    8. </Response>

    代码:(和上面的代码简直一毛一样)

    1. #include <iostream>
    2. #include "pugiconfig.hpp"
    3. #include "pugixml.hpp"
    4. #include <string>
    5. using namespace std;
    6. int main()
    7. {
    8. pugi::xml_document doc;
    9. doc.load_file("test.xml");
    10. pugi::xml_node response = doc.child("Response");
    11. //遍历
    12. for (pugi::xml_node node = response.first_child(); node != nullptr; node = node.next_sibling())
    13. {
    14. //cout << node.child_value() << endl; //两种访问方式
    15. cout << node.name() << ": " << node.text().as_string() << endl;
    16. }
    17. //特定访问
    18. pugi::xml_node sn = response.child("SN");
    19. cout << "SN: " << sn.child_value() << endl;
    20. system("pause");
    21. return 0;
    22. }

    ————————————————
    版权声明:本文为CSDN博主「这个名字不知道有没有人用啊」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/weixin_43272766/article/details/89875062