19

Boost 有一个关于如何从文件加载 XML 的教程。如何使用我在代码中创建或从用户接收的字符串(例如使用cin)来提供它?

4

3 回答 3

13

这是一些对我有用的代码......

// Create an empty property tree object
ptree xmlTree;

// Read the XML config string into the property tree. Catch any exception
try {
  stringstream ss; ss << xmlConfigString;
  read_xml(ss, xmlTree);
}
catch (xml_parser_error &e) {
  LOGERROR ("Failed to read config xml " << e.what());
}
catch (...) {
  LOGERROR ("Failed to read config xml with unknown error");
}
于 2011-12-16T15:54:58.327 回答
12

将字符串包裹在一个istringstream.

于 2011-03-13T11:35:00.773 回答
10

其他答案并不理想,因为使用istringstream不必要地复制了整个缓冲区。

正如对这个问题的回答所暗示的那样,您可以使用 deprecated istrstream,但是由于这会产生警告并且将来可能会被删除,因此更好的解决方案是使用boost::iostreams

boost::iostreams::stream<boost::iostreams::array_source> stream(moo.c_str(), moo.size());
boost::property_tree::read_json(stream, tree);

这避免了以相同的方式不必要地复制缓冲区istrstream(如果您的输入缓冲区很大,这可能是一个相当大的问题),并且您不必编写自己的流类。

于 2016-06-08T21:06:18.900 回答