8

Consider the following code using boost::property_tree:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
using namespace boost::property_tree;

int main() {
    ptree model_tree;
    model_tree.add("calibrated", "true");
    model_tree.add("model.<xmlattr>.label", "label");
    model_tree.add("model.activity.<xmlattr>.type", "fixed");
    write_xml("test.xml", model_tree);
}

By compiling and executing the program I get the following output:

<?xml version="1.0" encoding="utf-8"?>
<calibrated>true</calibrated><model label="label"><activity type="fixed"/></model>

Which is not really what I expected, as there are no new lines nor indentation. I would like to get the following instead:

<?xml version="1.0" encoding="utf-8"?>
<calibrated>true</calibrated>
<model label="label">
    <activity type="fixed"/>
</model>

Is it a bug, or is there an option to obtain the latter output? Any help would be appreciated.

P.S.: I am using Ubuntu 12.04 LTS with gcc 4.6.3 and boost 1.48.

gregory
  • 211
  • 2
  • 7
  • 1
    You should make your answer into a proper answer so we can (a) upvote it (b) it can be found http://meta.stackexchange.com/questions/12513/should-i-not-answer-my-own-questions – sehe Nov 30 '13 at 21:31

3 Answers3

13

In the meantime I've found the answer. One should use xml_writer_settings, that is:

xml_writer_settings<char> settings(' ', 4);
write_xml("test.xml", model_tree, std::locale(), settings);

The first parameter in the constructor is the character used for indentation, whilst the second is the indentation length. As the solution is undocumented, hopefully this will help others facing similar problems.

gregory
  • 211
  • 2
  • 7
  • 11
    Tested on MS Visual Studio 2013 with Boost 1.57: the `xml_write_settings` object must be templatized on `std::string` rather than `char`--it becomes: `xml_writer_settings settings(' ', 4);` – Julien-L Mar 26 '15 at 01:55
  • @Julien-L, correct. And if it is to the console: ` boost::property_tree::xml_writer_settings settings(' ', 4); boost::property_tree::write_xml(std::cout, pt, settings);` – alfC Sep 23 '17 at 01:57
2

Use settings while write_xml

settings Parameters

1.character indent
2:repeat times

boost::property_tree::xml_writer_settings<char> settings('\t', 1);
write_xml("xmlfilePath.xml", pt, std::locale(), settings);
Vinoj John Hosan
  • 6,448
  • 2
  • 41
  • 37
2

With (at least) boost 1.58, you can try this:

pt::write_xml( "test.xml", 
                model_tree,  
                std::locale(),
                pt::xml_writer_make_settings< std::string >( ' ', 4) );
Nikko
  • 4,182
  • 1
  • 26
  • 44