问题
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.
回答1:
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.
回答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);
回答3:
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) );
来源:https://stackoverflow.com/questions/20304701/no-end-of-line-in-boost-property-tree-xml-writer-output