2016-06-29 89 views
1

我正在使用tinyxml2,我想從C++中解析XML中的一些元素。例如解析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"); 
} 

當我嘗試「First」元素或「Second y」的同樣方法時,它只是顯示我的錯誤。我該怎麼辦?

+2

請顯示您的代碼。 – lorro

+0

打開tinyxml2教程,並使用它。 – Arkady

回答

0

您正在定義「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")); 

你的編譯器應該已經停止,雖然你,總是照顧警告!

+0

實際上這不是問題。我正在使用結構。我剛剛使用「第一」和「第二」作爲例子,這樣代碼對於一個問題就不會很大 –