How do I read content within tags with TinyXML?

269 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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;
}
0
On
int main()
{      
  TiXmlDocument *doc = new TiXmlDocument("simple-scene.xml"); 
  doc->LoadFile();

  TiXmlElement *root = doc->FirstChildElement("rt");
  TiXmlElement *image = root->FirstChildElement("image");
  TiXmlElement *width = image->FirstChildElement("width");

  cout << width->GetText();

  return 0;
}

Of course you have to add checks that FirstChildElement isn't returned NULL. Each time.