boost::property_tree XML pretty printing(boost::property_tree XML 漂亮打印)
问题描述
我正在使用 boost::property_tree 在我的应用程序中读取和写入 XML 配置文件.但是当我编写文件时,输出看起来有点难看,文件中有很多空行.问题是它也应该由人类编辑,所以我想获得更好的输出.
I'm using boost::property_tree to read and write XML configuration files in my application. But when I write the file the output looks kind of ugly with lots of empty lines in the file. The problem is that it's supposed to be edited by humans too so I'd like to get a better output.
举个例子,我写了一个小测试程序:
As an example I wrote a small test program :
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
int main( void )
{
using boost::property_tree::ptree;
ptree pt;
// reading file.xml
read_xml("file.xml", pt);
// writing the unchanged ptree in file2.xml
boost::property_tree::xml_writer_settings<char> settings(' ', 1);
write_xml("file2.xml", pt, std::locale(), settings);
return 0;
}
file.xml 包含:
file.xml contains:
<?xml version="1.0" ?>
<config>
<net>
<listenPort>10420</listenPort>
</net>
</config>
运行后的程序file2.xml包含:
after running the program file2.xml contains:
<?xml version="1.0" encoding="utf-8"?>
<config>
<net>
<listenPort>10420</listenPort>
</net>
</config>
除了手动查看输出并删除空行之外,还有什么方法可以获得更好的输出?
Is there a way to have a better output, other than going manually through the output and deleting empty lines?
推荐答案
解决方案是在对 read_xml
的调用中添加 trim_whitespace
标志:
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(' ', 1);
write_xml("file2.xml", pt, std::locale(), settings);
return 0;
}
该标志记录在此处 但该库的当前维护者 (Sebastien Redl) 很友好地回答并指出了它.
The flag is documented here but the current maintainer of the library (Sebastien Redl) was kind enough to answer and point me to it.
这篇关于boost::property_tree XML 漂亮打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:boost::property_tree XML 漂亮打印


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01