A Template-Based Approach to XML Parsing in C++
XML is a markup-based data description language designed to allow developers to create structured documents using descriptive custom tags. The intent of XML is to separate the description of the data from its intended use and allow the transfer of the data between different applications in a nonplatform- or architecture-specific way. Another useful application of XML is to describe a process in a logical and meaningful manner that can be carried out by the application at runtime.
In order for an XML file to be parsed successfully, the developer must first create a file that can be processed by a parser. A parser is a set of shared objects or a library that reads and processes an XML file.
The parser may be one of two types: validating or nonvalidating. A validating parser scans the XML file and determines if the document is well formed, as specified, by either an XML schema or the document type definition (DTD). A nonvalidating parser simply reads the file and ignores the format and layout as specified by either the XML schema or the DTD.
The most widely used parsers represent two different approaches: event-driven and tree-based. The event-driven parser is called SAX (simple API for XML processing). A tree-based parser creates a DOM (document object model) tree in memory at the time the XML file is read and parsed.
The DOM implementation is difficult to navigate and does not allow for clean mapping between XML elements and domain-specific objects. SAX provides the events to allow developers to create their domain-specific objects at the time the XML file is read and parsed. This article delivers a framework design using the SAX API for XML parsing.
The two most commonly used parsers for C++ are the open-source Xerces of the Apache Project and XML4C created by IBM's alphaWorks Project. XML4C is based on Xerces.
Both parsers essentially provide the same layout of source and libraries and therefore can be used interchangeably. They also support both DOM- and SAX-based XML parsing.
This document describes an implementation using the SAX parser with the Xerces parser. The Xerces source or binaries related to XML parsing can be downloaded from the Xerces web site (see Resources).
In order to begin parsing an XML file using the SAX API, the layout of the SAX C++ object interactions must be understood. SAX is designed with two basic interfaces:
SAXParser
setDoValidationsetDoNamespacesetDoSchemasetValidationFullSchemaCheckingsetDocumentHandlersetErrorHandlerparse
and
HandlerBase
warningerrorfatalErrorstartElementcharactersignorableWhitespaceendElement
Close examination of the methods in the HandlerBase object reveals two different categories of methods: error handling and document processing. The error-handling methods include warning, error and fatalError, whereas the parsing methods consist of startElement, characters, ignorableWhitespace and endElement. These behaviors can be separated into individual objects, as shown later.
The SAXParser class takes care of setting basic properties and the desired behavior to be enforced at runtime.
The following sample code illustrates the basic steps for parsing an XML file using the SAX parser in C++:
// Create a new instance of the SAX parser
SAXParser parser;
// Initialize the behavior you desire
parser.setDoValidation(true);
parser.setDoNamespaces(true);
parser.setDoSchema(true);
parser.setValidationSchemaFullChecking(true);
// Add handlers for document and error processing
parser.setDocumentHandler(&docHandler);
parser.setErrorHandler(&errorHandler);
// Parse file
parser.parse("MyXMLFile.xml");
At the time the parsing occurs, the classes you've instantiated, docHandler and errorHandler, are forwarded the events that get triggered from the parsing. These classes are derived from the Xerces base class HandlerBase and have overridden the appropriate methods for handling the events based on their categorized function.
Now that we've been exposed to parsing XML using SAX, let's explore how our XML framework has been implemented to take advantage of the facilities provided within the API.
A policy class, as described and made popular by Andrei Alexandrescu's Modern C++ Design (see Resources), “defines a class interface or a class template interface. The interface consists of one or all of the following: inner type definitions, member functions and member variables.”
The usefulness of policy classes, in this XML framework, are realized when created using a template-based C++ design. A policy allows you to parameterize and configure functionality at a fine granularity. In this design, policies are created to accommodate the following behaviors: document handling, error handling, domain mapping and parsing.
Configuring these elements as policies allows the creation of more concise code that is easier to maintain by any developer experienced in C++ and the use of templates.
The principal class of the XML-parsing framework is the XMLSAXParser. It's a custom-designed class template that implements the XMLParserInterface and includes a SAXParser object as a member variable. The template parameters include policy classes for both the document and error handlers. All parsing is eventually delegated to the SAXParser member variable after the various handlers and other properties have been set.
Implementing custom handlers, as policy classes, is a relatively trivial task using the framework. The advantage of this type of design is that the same framework can be used with different parsing APIs and different domain-mapping objects by altering one or more of the policies—an exercise that is not implemented in this article.
In order to create custom handlers, derive newly created custom classes from HandlerBase and override the virtual methods of interest. The following two types of custom handlers have been created in the XMLFactory framework:
XMLSAXHandler
startElementcharacterignorableWhitespaceendElement
and
XMLSAXErrorHandler
warningerrorfatalError
XMLSAXHandler handles document event processing, and XMLSAXErrorHandler handles the various error callbacks.
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Designing Electronics with Linux
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Reply to comment | Linux Journal
5 hours 45 min ago - Reply to comment | Linux Journal
6 hours 1 min ago - Favorite (and easily brute-forced) pw's
7 hours 52 min ago - Have you tried Boxen? It's a
13 hours 44 min ago - seo services in india
18 hours 16 min ago - For KDE install kio-mtp
18 hours 16 min ago - Evernote is much more...
20 hours 16 min ago - Reply to comment | Linux Journal
1 day 5 hours ago - Dynamic DNS
1 day 5 hours ago - Reply to comment | Linux Journal
1 day 6 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




Comments
Sample Code
Hey this code doesn't work. Missing XMLCommand.h. Please provide the same.
Regards
code with out using in built functions
xml parsing program
without using in built functions
Hi, I can't make the code
Hi,
I can't make the code compile..
One file is missing: XMLCommand.h.
can you supply it?
thanks,
XMLCommand.h
Hi John,
Can you please share the XMLCommand.h?
-Gunjan
sample code
Hi,
sounds interesting, but I can't make the code compile..
One file is missing: XMLCommand.h.
can you supply it?
thanks,
pierre