Link to home
Create AccountLog in
Avatar of prain
prainFlag for United States of America

asked on

How to read this XML using tinyxml

I have this XML file...
<?xml version="1.0"?>

<Data>
  <!-- data-->

  <Packet>
    <Name>Buffer</Name>
      <Value>v1</Value>
      <Item>myitem1</Item>
      <Item>myitem2</Item>
      <Item>myitem3</Item>
      <Item>myitem4</Item>
  </Packet>
</Data>

above is the pattern of the XML i have and cannot change the pattern (strictly).
Using tinyxml in C++, I want to read each <Item> and stack it into a vector.

I am having problems to extact each <Item>. In order to do that I should by pass/ignore <Name> and <Value>. Can some one show me how to do this..using tiny xml.

Here's what I have tried so far.

void readXML()
{

 TiXmlDocument document("myfile.xml");
 bool loadOk = doument.LoadFile();
   
 if (loadOk)
 {
    TiXmlElement *currentElement = document.RootElement()->FirstChildElement();
    while (currentElement != NULL)
    {
       std::string elementType = currentElement->ValueStr();
       if (elementType == "Item")
       {
           std::cout <<   elementType << std::endl;
           //I am just printing here. I can put it to a vector later.
       }

       currentElement = currentElement->NextSiblingElement();
    }

  }
}
Avatar of jkr
jkr
Flag of Germany image

And what is the problem you are having here?
Avatar of prain

ASKER

It does not get into the <Item>
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of prain

ASKER

Cool. Thank you!.
Avatar of prain

ASKER

OK I know I closed this Q. but I am having problems getting the actual value inside <Item> tags. So in the block,...

if (elementType == "Item")
       {
         //How to get the actual value "Myitem1" inside <Item>Myitem1</Item>
 
       }
Avatar of prain

ASKER

OK I found it. Thanks. Ignore previous request.
The simplest way would be to call 'GetText()' (or any appropriate other method, see http://www.grinninglizard.com/tinyxmldocs/classTiXmlElement.html), e.g.

  std::string text = currentElement->GetText();

Open in new window