A simple xml parser

The goal of this project was a simple to use xml-parser for utilization in the context of object-oriented programming where it is often enough for objects to write all their properties and subobjects into a file and read it in again. Therefor an operator-interface was defined that mimics the c++-I/O-streaming operators. It can be used like this
  #include "xml.h"
  using namespace XML;
  using namespace XML_Operators;

  XML::IElement* xmlElement = xmlConstructElement("TopElement");
  /* An output handle to the xml-element */
  element_handle_t out(*xmlElement);

  /* Write a few simple attributes */
  out
    <<comment("Element comment")
    <<"AnAttribute"<<attributeValue
    <<"AnotherAttribute"<<anotherValue;
    
  /* Write subelements */
  int values[]={0,1,2,3,4,5,6,7,8,9};
  
  for(unsigned i=0; i<<10; ++i)
  {
    out
      <<element("SubElement")
      <<text("These elements have text")
      <<"AttributeName"<<values[i]
      <<ende;
  }
  out<<ende;
  
  /* Write to file with comments but uncompressed */
  xmlElement->toFile("test.xml", true, false);
  
  xmlFreeElement(xmlElement);
Input is analogous.
  XML::IElement *xmlElement = xmlParseFile("test.xml");
  if(!xmlElement) exit(1);

  element_handle_t in(*xmlElement);
  
  int value;
  
  in
    >>"AnAttribute">>value
    /* ... */
    ;
    
   element_handle_t subElem;
   while( subElem = in>>element("SubElement") )
   {
      std::string txt;
      subElem
        >>text(txt)
        >>"AttributeName">>value;
        
      cout<<value<<endl;
   }
   xmlFreeElement(xmlElement);
The pitty is that I wrote not only the operators-interface but also the underlying XML-parser: A procedure I undertook only because of lacking an internet-connection after a move. As implementing a standard-conforming validating XML-parser is a huge project for itself, the underlying implementation only implements a subset of XML, has no means of validating XML-documents against XML-schemas and does not know about default-values of attributes. This means that, as error handling would break the beauty of the streaming-operator interface, one has to rely on valid input files or test the values read in the program - which should not be done as it unnecessarily bloats the code (that is why validating xml-parsers would be handy). Maybe I will switch the underlying parser implementation for a real xml-parser when I continue work on it. For more details on differences to the standard read the top of xml.h.
Source code can be downloaded here



Back to home
Copyright (C) 2012 Heiko Lewin