This problem is the biggest mistake in the iostream library.
James Kanze's solution is partial, which will work in your own classes, but overall, objects are provided with a great way to stream.
My usual way is to create your own wrapper class with a function that you can pass into your stream, and with xml it will contain overloads up to xml_node()
or xml_attribute()
for example.
os << xml_attribute( "Id", id );
sets the attribute identifier to a value that is in the variable in xml format.
I also wrote node areas so that they record the stream of node-opening text by construction and automatically record the closing logic upon destruction.
The advantage of my method over James Kanze's solution is that it is extensible. I think the comment by James Kanze suggests that he does not support his decision and is likely to use something more than mine.
With the above solution, to add more formats, you need to edit the <<operator is ubiquitous, while the json formatting code will be a completely different set of functions, and if you added another format, you would add code for it without having to edit any existing code.
For input, by the way, for XML, you would use the existing DOM or SAX parser and not use iostream in this way.
source share