我正在尝试使用属性作为关键字来查找我想要的元素。它可以工作,但只有当它是第一个元素时。
bool readXML(){
string gateWay_str="",user_Input="";
XMLDocument XML_file;
XML_file.LoadFile("exception_ip.xml"); //XML file Name
XMLHandle docHandle( &XML_file ); //XMLHandle
XMLNode* node_ctrl; //Node pointer
XMLElement* gateWay_Ele = docHandle.FirstChildElement("exception_ip").FirstChildElement("ip").ToElement(); //Get Node by XMLHandle and turn to Element
cout<<"Test ip3="; //show to user
cin>>user_Input; //user input
if(gateWay_Ele){ //is gateWay_Ele null?
gateWay_str=gateWay_Ele->Name(); //get Element name and show
cout<< "Got gateWay_Ele = "<<gateWay_str<<endl;
}
if(gateWay_Ele ->Attribute("ip3",(user_Input.c_str()))){ //find Attribute where ip3 = "user input"
node_ctrl=gateWay_Ele->FirstChild(); //make node_ctrl point FirstChild
if(node_ctrl==nullptr){ //is nullptr?
cout<<"node_ctrl = nullptr";
return false;
}
else{
gateWay_Ele=node_ctrl->ToElement(); //turn node_ctel to Element
gateWay_str = gateWay_Ele->GetText(); //get Text
cout<<"GateWay = "<<gateWay_str<<endl; //show
return true; //return true
}
}
return false;
}
我的 XML 是
<?xml version="1.0" ?>
<exception_ip>
<ip ip3="23">
<gateway>123.123.23.1</gateway>
<dnsp>dnsp23</dnsp>
<dnss>dnss23</dnss>
</ip>
<ip ip3="24">
<gateway>123.123.24.1</gateway>
<dnsp>dnsp24</dnsp>
<dnss>dnss24</dnss>
</ip>
</exception_ip>
仅在输入为 23 时有效
并且我曾尝试使用 NextSiblingElement("ip") 来说明继续转到下一个兄弟元素。但它只是无限循环
do{
if(gateWay_Ele ->Attribute("ip3",(user_Input.c_str()))){ //find Attribute where ip3 = "user input"
node_ctrl=gateWay_Ele->FirstChild(); //make node_ctrl point FirstChild
if(node_ctrl==nullptr){ //is nullptr?
cout<<"node_ctrl = nullptr";
return false;
}
else{
gateWay_Ele=node_ctrl->ToElement(); //turn node_ctel to Element
gateWay_str = gateWay_Ele->GetText(); //get Text
cout<<"GateWay = "<<gateWay_str<<endl; //show
return true; //return true
}
}
else{
gateWay_Ele->NextSiblingElement("ip");
}
}while(true);
谢谢 !