Boost property tree (XML) remove blank lines

2k views Asked by At

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.

2

There are 2 answers

0
mattu On BEST ANSWER

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

3
FallenWarrior On

Not Boost, but blank lines in particular. You can use std::regex_replace() on the output before it is written to the file, removing the blank lines, like this

std::regex_replace(std::ostreambuf_iterator<char>(fout), text.begin(), text.end(), std::regex("(\\n+)"), "\n");

With fout as the file output stream and text as the output data as a std::string.

This replaces every newline followed by another newline w/o any characters in between with a single newline.