A Template-Based Approach to XML Parsing in C++

Using the Xerces library and a little C++ code, you can parse an XML file to get only the information you need as easy-to-handle objects.
Mapping XML Tags to Domain Objects

The next aspect of our XML-parsing framework is converting XML tags into domain-related objects that can be used within the application by using templates and a loose definition of policy classes.

The XMLDomainMap template accepts a single template parameter, called an XMLNode. The interface for the domain-mapping object is as follows:

XMLDomainMap

createaddupdateAttribute

The XMLNode acts as both a leaf and a root in a tree structure that aggregates its children as a subtree. The XMLNode's interface is:

XMLNode

operator==operator!=operator=addChildhasChildrennumChildrenvaluenamegetChildCountgetChildgetParent

The key here is the design of the public interface of the object. There are several operator overloads, specifically operator equals (operator==), operator not equals (operator!=) and the assignment operator (operator=). The benefit to this is the object now can be used with many standard template library (STL) containers and algorithms, which allows for the use of advanced features with the C++ language.

Linking our Classes Together—An XML Façade

Thus far, the focus has been on individual classes and describing the templates that have been created for our XML-processing framework. The next step is to link the disparate interfaces together and make them appear to function as a single cohesive unit by using the façade design pattern.

The façade design provides a simple and elegant way to delegate parsing functionality from an outside client to the internal policy class that will be used for performing the parsing.

In Design Patterns, the authors define the intent as to “Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.”

The XMLProcessor is the façade that has been created. It is defined with the following interface:

XMLProcessor

parsegetParseEngine

Once all the source has been written, an XML file and a test client will be needed to run our sample.

Parsing an Actual XML File

The following simple XML file, showing the basic layout of a customer record with a name and account number, has been created to illustrate the simplicity of using the framework:

<?xml version="1.0"
encoding="iso-8859-1"?>
<customer>
    <name>John Doe</name>
    <account-number>555123</account-number>
</customer>

For now, create this file with a text editor and save it as MyXMLFile.xml.

The Public Interface—Writing the Client Application

The framework's functionality will be used as a mechanism to provide a succinct interface to the client application.

The primary methods that a client of the framework would make use of can be described with an actual, albeit small, sample of C++ source code:

// ---------------------------------------
//  Sample source for parsing an XML doc
// ---------------------------------------
#include "XMLProcessor.hpp"
#include "XMLDomainMap.hpp"
#include "XMLSAXParser.hpp"
#include "XMLNode.hpp"
#include "XMLCommand.h"
#include "XMLSAXHandler.hpp"
#include "XMLSAXErrorHandler.hpp"
#include <iostream>
using namespace std;
using namespace XML;
// Let's get the ugly stuff out of the way first
typedef XMLSAXHandler<XMLDomainMap<XMLNode> >
  DOCHANDLER;
typedef XMLSAXErrorHandler ERRORHANDLER;
typedef XMLSAXParser<DOCHANDLER, ERRORHANDLER>
  PARSER;
typedef XMLProcessor<PARSER> XMLEngine;
// Create a basic test client
int main(void)
{
    // Define a string object with our filename
    std::string xmlFile = "MyXMLFile.xml";
    // Create an instance of our XMLFactory
    XMLEngine parser(xmlFile);
    // Turn off validation
    parser.doValidation(false);

    // Parse our XML file
    parser.parse();
    // Get the tree root
    XMLNode root = parser.getXMLRoot();
    // Print the name of our object
    cout << "Root = " << root.name() <<
endl;
    return 0;
}

Now that an instance of an XMLNode object representing the root of the tree has been parsed, the child elements of the root XMLNode can be accessed.

Compiling the Test Client

The last step is to compile the client. Simply perform the compile at the command line:

g++ -o testClient -I. -I/path/to/xerces/include \
-I/path/to/xerces/include/xerces testClient.cpp \
-L/path/to/xerces/lib -lxerces-c

This compiles the client application. The next step is to run a test. Be sure to set your LD_LIBRARY_PATH environment variable to point to the location of your Xerces installation's lib directory. Because the shared libraries are from this directory, the application loader needs a way to import the required symbols at runtime in order for everything to function correctly.

When testClient is run, the following output is expected:

$>testClient
Adding child name
Adding child account-number
Root = customer

You now have a fully functional XML-parsing framework using C++ templates that will allow you to incorporate XML into your new or existing applications. Sample code is available at ftp.linuxjournal.com/pub/lj/listings/issue110/6655l1.tgz.

Resources

email: jdubchak@qwest.net

John Dubchak is a senior software developer working as a consultant in the St. Louis area. He's been programming in C++ for the past 12 years and can't believe how bad his first lines of C++ actually were. His wife says that his hobby is “sitting at the computer writing little programs”.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Sample Code

Anonymous's picture

Hey this code doesn't work. Missing XMLCommand.h. Please provide the same.
Regards

code with out using in built functions

ravi's picture

xml parsing program
without using in built functions

Hi, I can't make the code

Anonymous's picture

Hi,
I can't make the code compile..
One file is missing: XMLCommand.h.
can you supply it?

thanks,

XMLCommand.h

Gunjan's picture

Hi John,

Can you please share the XMLCommand.h?

-Gunjan

sample code

pierreG's picture

Hi,
sounds interesting, but I can't make the code compile..
One file is missing: XMLCommand.h.
can you supply it?

thanks,

pierre

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix