I want to parse some data from an xml file with TinyXML.
Here's my text.xml file content:
<?xml version="1.0" encoding="iso-8859-1"?>
<toto>
<tutu>
<tata>
<user name="toto" pass="13" indice="1"/>
<user name="tata" pass="142" indice="2"/>
<user name="titi" pass="azerty" indice="1"/>
</tata>
</tutu>
</toto>
I want to access to the first element 'user'. The way to do this is the following :
TiXmlDocument doc("test.xml");
if (doc.LoadFile())
{
TiXmlNode *elem = doc.FirstChildElement()->FirstChildElement()->FirstChildElement()->FirstChildElement();
std::cout << elem->Value() << std::endl;
}
In output : user.
But the code is pretty ugly and not generic. I tried the code below to simulate the same behaviour than the code above but it doesn't work and an error occured.
TiXmlElement *getElementByName(TiXmlDocument &doc, std::string const &elemt_value)
{
TiXmlElement *elem = doc.FirstChildElement(); //Tree root
while (elem)
{
if (!std::string(elem->Value()).compare(elemt_value))
return (elem);
elem = elem->NextSiblingElement();
}
return (NULL);
}
Maybe I missed a special function in the library which can do this work (a getElementByName function). I just want to get a pointer to the element where the value is the one I'm looking for. Does anyone can help me? Thanks in advance for your help.
Try this
TiXmlElement * getElementByName(TiXmlDocument & doc, std::string const & elemt_value) {
TiXmlElement * elem = doc.RootElement(); //Tree root
while (elem) {
if (!std::string(elem - > Value()).compare(elemt_value)) return (elem);
/*elem = elem->NextSiblingElement();*/
if (elem - > FirstChildElement()) {
elem = elem - > FirstChildElement();
} else if (elem - > NextSiblingElement()) {
elem = elem - > NextSiblingElement();
} else {
while (!elem - > Parent() - > NextSiblingElement()) {
if (elem - > Parent() - > ToElement() == doc.RootElement()) {
return NULL;
}
elem = elem - > Parent() - > NextSiblingElement();
}
}
}
return (NULL);
}