c++ - boost::property_tree XML pretty-print

标签 c++ boost boost-propertytree

我正在使用 boost::property_tree 在我的应用程序中读取和写入 XML 配置文件。 但是当我编写文件时,输出看起来有点难看,文件中有很多空行。 问题是它也应该由人类编辑,所以我想获得更好的输出。

作为一个例子,我写了一个小测试程序:

#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('\t', 1);
    write_xml("file2.xml", pt, std::locale(), settings);

    return 0;
}

file.xml 包含:

<?xml version="1.0" ?>
<config>
    <net>
        <listenPort>10420</listenPort>
    </net>
</config>

运行程序后file2.xml包含:

<?xml version="1.0" encoding="utf-8"?>
<config>



    <net>



        <listenPort>10420</listenPort>
    </net>
</config>

除了手动通过输出和删除空行之外,有没有更好的输出方法?

最佳答案

解决方案是将 trim_whitespace 标志添加到对 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('\t', 1);
    write_xml("file2.xml", pt, std::locale(), settings);

    return 0;
}

标记已记录 here但是该库的当前维护者 (Sebastien Redl) 非常友好地回答并指出了它。

关于c++ - boost::property_tree XML pretty-print ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6572550/

相关文章:

c++ - 在 iPhone xcode 应用程序中,是否可以声明具有全局范围的指针?

c++ - 如何线程化作为类方法的可调用函数

c++ - 面向低延迟大数据交换的多线程boost C++程序设计

c++ - 有没有一种方便的方法可以从属性树中删除节点,同时保留其子节点?

c++ - boost::property_tree 传递包含 <xmlattr> 的子树

c++ - 在 Visual Studio 中记录 CPU 使用情况

c++ - 如何将编译扩展到函数或循环

c++ - 使用属性树在 boost 中解析 xml

c++ - 读取和解析 JSON 文件 C++ BOOST

c++ - 声明 `const` `boost::range` s 的正确方法