Search code examples
c++boostboost-propertytree

boost::property_tree XML pretty printing


I'm using boost::property_tree to read and write XML configuration files in my application. But when I write the file the output looks kind of ugly with lots of empty lines in the file. The problem is that it's supposed to be edited by humans too so I'd like to get a better output.

As an example I wrote a small test program :

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

int main( void )
{
    using boost::property_tree::ptree;
    ptree pt;

    // reading file.xml
    read_xml("file.xml", pt);

    // writing the unchanged ptree in file2.xml
    boost::property_tree::xml_writer_settings<char> settings('\t', 1);
    write_xml("file2.xml", pt, std::locale(), settings);

    return 0;
}

file.xml contains:

<?xml version="1.0" ?>
<config>
    <net>
        <listenPort>10420</listenPort>
    </net>
</config>

after running the program file2.xml contains:

<?xml version="1.0" encoding="utf-8"?>
<config>



    <net>



        <listenPort>10420</listenPort>
    </net>
</config>

Is there a way to have a better output, other than going manually through the output and deleting empty lines?


Solution

  • The solution was to add the trim_whitespace flag to the call to read_xml:

    #include <boost/property_tree/ptree.hpp>
    #include <boost/property_tree/xml_parser.hpp>
    
    int main( void )
    {
        // Create an empty property tree object
        using boost::property_tree::ptree;
        ptree pt;
    
        // reading file.xml
        read_xml("file.xml", pt, boost::property_tree::xml_parser::trim_whitespace );
    
        // writing the unchanged ptree in file2.xml
        boost::property_tree::xml_writer_settings<char> settings('\t', 1);
        write_xml("file2.xml", pt, std::locale(), settings);
    
        return 0;
    }
    

    The flag is documented here but the current maintainer of the library (Sebastien Redl) was kind enough to answer and point me to it.