xml - How to use Attribute as search keyword with TinyXML2(C++) -
i'm trying use attribute keyword find element want. can work when first element.
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 xmlhandle , turn element cout<<"test ip3="; //show user cin>>user_input; //user input if(gateway_ele){ //is gateway_ele null? gateway_str=gateway_ele->name(); //get element name , show cout<< "got gateway_ele = "<<gateway_str<<endl; } if(gateway_ele ->attribute("ip3",(user_input.c_str()))){ //find attribute 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 element gateway_str = gateway_ele->gettext(); //get text cout<<"gateway = "<<gateway_str<<endl; //show return true; //return true } } return false; }
and 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> it work when input 23
and had tried use nextsiblingelement("ip") make point keep going next sibling element. infinite loop
do{ if(gateway_ele ->attribute("ip3",(user_input.c_str()))){ //find attribute 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 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); thanks !
you need iterate on "ip" elements, testing "ip3" attribute until find 1 want. here's easy way using my tinyxml2 extension :
#include <string> #include <iostream> #include <conio.h> // _getch() // include header tinyxml2ex includes tinyxml2, remember put them on include path #include "tixml2ex.h" using namespace std; int main() { // put xml string simplicity string testxml{ r"-( <?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> )-"s }; auto doc = tinyxml2::load_document (testxml); // find required element xpath , list member elements if (auto ip = find_element (*doc, "/exception_ip/ip[@ip3='24']"s)) { (auto e : ip) cout << e->name() << " " << text (e) << endl; } else cout << "could not find ip element" << endl; return 0; }
Comments
Post a Comment