sourcecode

Friday, February 22, 2013

xml intro

First impression to XML parsing using RapidXML lib in C++
http://rapidxml.sourceforge.net/

Example XML from here:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms762271%28v=vs.85%29.aspx

Test code under the same folder of the RapidXML:


#include <iostream>
#include <sstream>
#include <fstream>

#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"


using namespace std;
using namespace rapidxml;

 char *buffer_file( const char *filename, size_t *buffer_len = NULL )
 {
  //open file.  note: it is important to say binary here, otherwise it does conversion that may change the length!
  std::fstream file( filename, std::ios::in|::std::ios::binary );
  if( !file ) return NULL;

  //read the size...
  file.seekg(0, std::ios::end);
  size_t length = (size_t)file.tellg();
  if( buffer_len ) *buffer_len = length;
  file.seekg(0, std::ios::beg);
  
  //read into memory buffer..
  char *filebuf = new char[length+1];
  file.read(filebuf, length);
  filebuf[length] = '\0'; //make it null-terminated
  file.close();
  return filebuf;
 }


int main(int argc, char* argv[]) {
    char* xml = buffer_file("books.xml");

    //Parse the original document
    xml_document<> doc;
    doc.parse<0>(xml);
    xml_node<> * node = doc.first_node();
    cout << "Name of my first node is: " << node->name() << "\n";
for( xml_node<>* node_ptr = node->first_node("book"); node_ptr != NULL; node_ptr = node_ptr->next_sibling())

    cout<< "node name : " << node_ptr->first_attribute("id")->value()<< endl;
    return 0;
}

No comments: