打印boost属性树生成的xml

Printing the xml generated by the boost property tree

本文关键字:xml boost 属性 打印      更新时间:2023-10-16

我测试了boost::property_tree,它很好:我可以加载XML,提取元素,保存XML等。但是,是否有可能生成XML并打印出来呢?我不想保存它。

void debug_settings::load(const std::string &filename) {
    using boost::property_tree::ptree;
    ptree pt;
    read_xml(filename, pt);
    m_file = pt.get<std::string>("debug.filename");
    m_level = pt.get("debug.level", 0);
    BOOST_FOREACH(ptree::value_type &v, pt.get_child("debug.modules"))m_modules.insert(v.second.data());
}
void debug_settings::save(const std::string &filename) {
    using boost::property_tree::ptree;
    ptree pt;
    pt.put("debug.filename", m_file);
    pt.put("debug.level", m_level);
    BOOST_FOREACH(const std::string &name, m_modules)pt.add("debug.modules.module", name);
    write_xml(filename, pt);
}

这是我用来加载和保存XML的函数。我们有显示它的方法吗?

使用以下版本的函数

template<typename Ptree> 
  void write_xml
  (
     std::basic_ostream< typename Ptree::key_type::value_type > & stream, 
     const Ptree & pt, 
     const xml_writer_settings< typename Ptree::key_type::value_type > & settings = 
     xml_writer_settings< typename Ptree::key_type::value_type >()
  );
http://www.boost.org/doc/libs/1_52_0/doc/html/boost/property_tree/xml_parser/write_xml_id1233444.html

write_xml(std::cout, pt);

用于在控制台

中输出
std::ostringstream oss;
write_xml(oss, pt);

用于stringstream的输出(可通过stringstreamstr功能在控制台输出stringstream内容)。

http://liveworkspace.org/code/4qV9om 4美元

您可以使用任何类型的输出流,因此std::cout可以很好地将XML打印到当前控制台