How to feed Boost.PropertyTree with a string, not a file?
Asked Answered
H

3

20

Boost has a tutorial on how to load XML from a file. How do I feed it with a string that I either create in code or receive from a user (e.g. with cin)?

Halpern answered 13/3, 2011 at 11:32 Comment(0)
B
12

Wrap the string in an istringstream.

Bloch answered 13/3, 2011 at 11:35 Comment(0)
F
13

Heres some code that works for me...

// 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");
}
Freitag answered 16/12, 2011 at 15:54 Comment(0)
B
12

Wrap the string in an istringstream.

Bloch answered 13/3, 2011 at 11:35 Comment(0)
M
10

The other answers are non-ideal, because using istringstream needlessly copies the entire buffer.

As an answer on this question suggests, you could use the deprecated istrstream, but as this generates warnings and may be removed in future, a better solution is to use boost::iostreams:

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

This avoids needlessly copying the buffer in the same way istrstream did (which can be a considerable problem, if your input buffer is large), and saves you having to write your own stream class.

Mccurry answered 8/6, 2016 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.