Search code examples
c++xmlboostformattingboost-propertytree

Boost property tree (XML) remove blank lines


I am using boost::property_tree to read and write xml configuration files. I want to change the value of some tags in my code and write them back to file, with some reasonable xml formatting (new lines, indenting, etc.).

Currently I am using

std::fstream fs("filename");
boost::property_tree::ptree pt;
bpt::xml_parser::read_xml(fs,pt);

// replace value
pt.erase("tagname");
pt.put("tagname",newval);

bpt::xml_parser::xml_writer_settings<char> xmlstyle(' ',4);
bpt::xml_parser::write_xml("filename",pt,std::locale(),xmlstyle);

But it seems that every time a tag is deleted, it leaves behind a blank line and after some iterations the xml becomes unreadable. Is there a way to remove empty lines from the property tree itself or from the resulting xml file using boost?

I know there are other ways of removing the newlines by reading and parsing the entire file again, but I was hoping for a more convenient one-liner.


Solution

  • Ok, it looks like the answer was already out there on Stack Overflow, I just hadn't found it (newlines were not mentioned in the post)

    boost::property_tree XML pretty printing

    The solution is to read the file with boost::property_tree::xml_parser::trim_whitespace