Chapter 65. Escaping XML strings

#include <x/xml/escape.H>

std::string str=x::xml::escapestr("<URL:>");

x::xml::escapestr() is a miscellaneous utility function replaces all occurences of the characters <, >, and & with &lt;, &gt;, and &amp;.

If the optional second parameter is specified as true, the ', ", and control characters (U+0x0000 to U+0x001F) get replaced with &#xN;, where N is the hexadecimal value of the replaced character.

A more generic alternative is the x::xml::escape() template function. This function defines a string using a beginning and an ending iterator. The replacement string is written to an output iterator. x::xml::escapestr(str, flag) is exactly equivalent to:

std::string s;

x::xml::escape(str.begin(), str.end(),
               std::back_insert_iterator<std::string>(s), flag);

return s;

The optional flag carries the same meaning as the optional parameter to x::xml::escape(). Furthermore, the beginning and the ending input iterators may iterate over integer values larger than a char or unsigned char. If so, integer values 0x80 and higher get also replaced by &#xN;.