boost::property_tree XML pretty printing

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.


This question is quite old, but I investigated your problem again, lately, because it got a lot worse now that property_tree translates newlines to

&#10;    

In my opinion this is a bug, because elements, which contains only whitespace - newlines, spaces and tabs, are treated as text elements. trim_whitespace is only a bandaid and normalizes ALL whitespace in the property_tree.

I reported the bug over here and also attached a .diff to fix this behaviour in Boost 1.59 in case trim_whitespace is not used: https://svn.boost.org/trac/boost/ticket/11600