Learning Poco: Load XML Configuration

http://www.codeproject.com/Articles/253418/Learning-Poco-Load-XML-Configuration

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:

<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:

#include <span class="code-keyword"><Poco/Util/AbstractConfiguration.h>
</span>#include <span class="code-keyword"><Poco/Util/XMLConfiguration.h>
</span>#include <span class="code-keyword"><iostream>
</span>
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.

// 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?