Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / XML

Learning Poco: Load XML Configuration

4.20/5 (5 votes)
12 Sep 2011CC (ASA 3U) 35.6K  
In this tutorial, we will load XML configuration from files ystem by using XMLConfiguration, and access specific configuration items by using methods provided by AbstractConfiguration.

In this tutorial, we will load an XML configuration from the file system by using XMLConfiguration, and access specific configuration items by using methods provided by AbstractConfiguration. Here, AbstractConfiguration is an interface, and XMLConfiguration is the implementation, both provided by Poco.

Prepare an XML configuration file called conf.xml like this:

XML
<config>
    <prop1>1.23</prop1>
    <prop2>2.34</prop2>
    <prop3>
       <prop4 attr="1"/>
       <prop4 attr="2"/>
    </prop3>
    <prop5 id="first">Hello,</prop5>
    <prop5 id="second"> world!</prop5>
</config>

Then create the source file xml_conf.cc:

C++
#include <Poco/Util/AbstractConfiguration.h>
#include <Poco/Util/XMLConfiguration.h>
#include <iostream>

using namespace Poco::Util;
using namespace std;

int main()
{
  AbstractConfiguration *cfg = new XMLConfiguration("conf.xml");

  double prop1 = cfg->getDouble("prop1");
  double prop2 = cfg->getDouble("prop2");
  cout << "prop1 + prop2 = " << prop1 + prop2 << endl;

  cout << "This is an empty string: " 
       << cfg->getString("prop3.prop4") << endl;

  int prop4   = cfg->getInt("prop3.prop4[@attr]");
  int prop4_0 = cfg->getInt("prop3.prop4[0][@attr]");
  int prop4_1 = cfg->getInt("prop3.prop4[1][@attr]");
  cout << "prop4 + prop4_0 + prop4_1 = " 
       << prop4 + prop4_0 + prop4_1 << endl;

  cout << cfg->getString("prop5[0]") 
       << cfg->getString("prop5[1]") << endl;
  cout << cfg->getString("prop5[@id=first]") 
       << cfg->getString("prop5[@id='second'") << endl;

  // No need to delete cfg, since it is reference counted for garbage collection

  return 0;
}

Compile it and run:

$ g++ -o xml_conf xml_conf.cc -lPocoUtil
$ ./xml_conf
prop1 + prop2 = 3.57
This is an empty string: 
prop4 + prop4_0 + prop4_1 = 4
Hello, world!
Hello, world!

That’s it!

The code above is very easy to understand, and notice that there is no need to delete cfg, since it is reference counted for garbage collection and will be deleted by Poco automatically. And you can not write like the following because the destructor of both AbstractConfiguration and XMLConfiguration are protected.

C#
// You can NOT write like this! It won't compile!
XMLConfiguration config("conf.xml");

So refactor your code and use it now! XML configuration is much more flexible than plain-text files, and Poco handles everything you need to work with a configuration file. Why not give it a try?

License

This article, along with any associated source code and files, is licensed under The Creative Commons Attribution-Share Alike 3.0 Unported License