在c++中解析XML元素

Parse XML elements in C++

本文关键字:XML 元素 c++      更新时间:2023-10-16

我使用的是tinyxml2,我想在c++中解析XML中的一些元素。例如

<root>
     <First x="1" y="2">
     <Second x = "1">
     <Second y = "2">
</root>

我只能解析"Second"元素中的x。

#include <stdio.h>
#include "tinyxml2.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace tinyxml2;
using namespace std;
int main(){
     tinyxml2::XMLError eResult = xml_doc.LoadFile("test.xml");
     if (eResult != tinyxml2::XML_SUCCESS) return false;
     tinyxml2::XMLNode* root = xml_doc.FirstChildElement("root");
     if (root == nullptr) return false;
     tinyxml2::XMLElement* First = root->FirstChildElement("First");
     if (First == nullptr) return false;
     double x1 = std::stod(First->Attribute("x"));
     double y1 = std::stod(First->Attribute("y"));
     tinyxml2::XMLElement* Second = root->FirstChildElement("Second");
     if (Second == nullptr) return false;
     double x2 = std::stod(Second->Attribute("x"));
     double y2 = std::stod(Second->Attribute("y"));
     system("pause");
}

当我为"第一个"元素或"第二个y"尝试相同的方法时,它只是向我显示错误。我该怎么办?

您定义了两次"double x"。试着

double first_x = std::stod(First->Attribute("x"));
double first_y = std::stod(First->Attribute("y"));

double second_x = std::stod(Second->Attribute("x"));

你的编译器应该已经阻止你了,但是一定要注意警告!