Reputation: 45
This should be a pretty easy question for people who have used TinyXML. I'm attempting to use TinyXML to parse through an XML document and pull out some values. I figured out how to add in the library yesterday, and I have successfully loaded the document (hey, it's a start).
I've been reading through the manual and I can't quite figure out how to pull out individual attributes. After Googling around, I haven't found an example of my specific example, so perhaps someone here who has used TinyXML can help out. Below is a slice of the XML, and where I have started to parse it.
XML:
<?xml version='1.0' encoding='UTF-8'?>
<hnisi>
<head><version>1.0</version></head>
<body>
<params>
<param key="FHZ" val="1" />
<param key="MSG" val="login failed" />
<param key="SESSIONID" val="HISID6B5FD5E290884C77A2BA827AA2B1E53D" />
</params>
</body>
</hnisi>
Loading/parsing code:
TiXmlDocument doc;
const char *filedate=response.return_->c_str();
doc.Parse(filedata, 0, TIXML_ENCODING_UTF8);
TiXmlElement *pRoot, *pParm, *pProcess, *pApp, *pLineFormat;
pRoot = XMLdoc.FirstChildElement( "hnisi" );
if ( pRoot )
{
pParm= pRoot->FirstChildElement( "params" );
while(pParm)
{
// I don't know here,how do I read the attribute of value of FHZ,MSG and SESSIONID?
}
}
Upvotes: 3
Views: 3357
Reputation: 6276
You missed to get the <body>
element, which is a child of <hnisi>
, and then you want to have the <param>
elements which are children of <params>
in your xml. To get the attributes just use the Attribute
function of TiXmlElement.
TiXmlDocument doc("yourfile.xml");
if(doc.LoadFile())
{
TiXmlElement *pRoot, *pBody, *pParms, *pProcess, *pApp, *pLineFormat, *pParm;
pRoot = doc.FirstChildElement( "hnisi" );
if ( pRoot )
{
pBody= pRoot->FirstChildElement( "body" ); //body should be read
if (pBody) {
pParms= pBody->FirstChildElement( "params" ); //now params
if(pParms)
{
pParm=pParms->FirstChildElement("param");
while (pParm) {
// now loop al param elements and get their attributes
std::cout <<"key="<<pParm->Attribute("key")<<std::endl;
std::cout <<"val="<<pParm->Attribute("val")<<std::endl;
//next sibling
pParm=pParm->NextSiblingElement("param");
}
}
}
}
}
Upvotes: 3