Search code examples
tinyxml

How do I read content within tags with TinyXML?


I'm trying to read content within tags, but I'm not succeeding.

Here's what I'm trying:

int main()
{      
  TiXmlDocument *doc = new TiXmlDocument("simple-scene.xml"); 
  doc->LoadFile();

  cout << doc->FirstChildElement("width")->GetText();

  return 0;
}

Here's the XML document:

<?xml version="1.0" encoding="utf-8"?>
<rt>
<image>
  <width>800</width>
  <height>600</height>
</image>
</rt>

Any help is appreciated!


Solution

  • You have to access from root element to the child elements such as this sample:

    int main()
    {      
      TiXmlDocument *doc = new TiXmlDocument("simple-scene.xml"); 
      doc->LoadFile();
    
      TiXmlElement* root = doc.FirstChildElement( "rt" );
      if ( root )
      {
         TiXmlElement* image = root->FirstChildElement( "image" );
         if ( image )
         {
            TiXmlElement* width = element->FirstChildElement( "width" );
            if ( width )
            {
                 std::string strWidth = width->GetText();
                 std::cout << width->Value();
            }
         }
      }
    
      return 0;
    }