C++中用Vector和pair灵活的存储用Tinyxml读出的内容

it2025-04-24  18

由于公司需要,做工业互联涉及到xml的读出,本来读出之后使用简单的变量作为存储,但是变量的方式又不好做到数据的归类,就想到了用Vector与pair结合的方式进行存储,水平有限,请大家多指教。

#pragma once #include <string> #include <vector> struct RegularItemNode { const char *Name; std::string Description; int Code; int Length; }; struct DeviceNode { const char *Name; std::string Description; const char * ParseRegularCode; };

上面为.h文件

.cpp文件涉及了用TinyXml文件解析xml文件以及内容的存储。具体内容如下:

char *XmlFilePath = (char *)"Data.xml"; TiXmlDocument doc; doc.LoadFile(XmlFilePath, TIXML_ENCODING_UTF8); TiXmlElement *root = doc.RootElement(); TiXmlElement *xml_node_Devices = root->FirstChildElement(); TiXmlElement *xml_node_Regular = xml_node_Devices->NextSiblingElement(); std::vector<std::pair<const char *, std::vector<RegularItemNode>>> list_regular; for (TiXmlElement *regularNode = xml_node_Regular->FirstChildElement(); regularNode; regularNode = regularNode->NextSiblingElement()) { if (!regularNode->NoChildren()) //如果节点有孩子 { const char *key = regularNode->Attribute("Name"); std::vector<RegularItemNode> list; //把里面一个vector单独拉出来定义 for (TiXmlElement *regularItemNode = regularNode->FirstChildElement(); regularItemNode; regularItemNode = regularItemNode->NextSiblingElement()) { if (regularItemNode->NoChildren()) { RegularItemNode model; //用RegularItemNode定义出model model.Name = regularItemNode->Attribute("Name"); model.Description = UTF8_To_String(regularItemNode->Attribute("Description")); model.Code = atoi(regularItemNode->Attribute("Code")); model.Length = atoi(regularItemNode->Attribute("Length")); list.push_back(model); //先把model里面的值装给所定义的第一个list } } list_regular.push_back(make_pair(key, list)); //把list里面的值先与key所绑定了,然后再装入list_regular } } std::vector<DeviceNode> list_DeviceNode; for (TiXmlElement *deviceNode = xml_node_Devices->FirstChildElement(); deviceNode; deviceNode = deviceNode->NextSiblingElement()) { if (!deviceNode->NoChildren()) { DeviceNode model; model.Name = deviceNode->Attribute("Name"); model.Description = UTF8_To_String(deviceNode->Attribute("Description")); TiXmlElement *xml_node_Devices_DeviceNode_DeviceRequest = deviceNode->FirstChildElement(); model.ParseRegularCode = xml_node_Devices_DeviceNode_DeviceRequest->Attribute("ParseRegularCode"); list_DeviceNode.push_back(model); } }

所读出的数据,会用Opcua创立节点,做成数据表格的形式。

具体的xml文件之后会添加(由于xml文件内容较为繁琐,所以读取与存储的代码也有些繁琐,见谅)。

最新回复(0)