Snapshot: leyendo archivos XML en C++ con TinyXML

by Jorge Machin on December 1, 2008 · 0 comments

in C/C++, Snapshots

La biblioteca TinyXML es muy liviana y permite parsear rapidamente XMLs sin tener que hacer mucho formalismo. En este post presento un código de ejemplo:

El xml que queremos parsear como ejemplo es el siguiente:

<?xml version="1.0">

<ELEMENT attribute="attribute">
   <CHILD>child</CHILD>
</ELEMENT>

A continuación el programa de ejemplo en c++ que realiza el parseo:

#include <iostream>

#include "tinyxml.h"

using namespace std;

int main() {

  TiXmlDocument doc;

  if ( !doc.LoadFile( "ejemplo.xml" ) )  {

    cout <<"Error: Can't load file ejemplo.xml" << endl;
    return EXIT_FAILURE;

  }

  string attribute, childi_value;

  TiXmlElement *element;

  element = doc.FirstChildElement( "ELEMENT" );

  if ( element->Attribute( "attribute" ) != NULL )

      attribute = string ( element->Attribute( "attribute" ) );

  cout <<"attribute: " <<attribute <<endl;

  TiXmlElement* child = element->FirstChildElement("CHILD");

  if ( child != NULL )

    child_value = string( ( ( child->FirstChild() )->ToText() )->Value() );

  cout <<"child value: " <<child_value <<endl;

  return EXIT_SUCCESS;

}

El cual compilamos con:

g++ -o main main.cpp -ltinyxml

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post:

Next post: