Is there c++ function that replace xml Special Character with their escape sequence? Is there c++ function that replace xml Special Character with their escape sequence? xml xml

Is there c++ function that replace xml Special Character with their escape sequence?


Writing your own is easy enough, but scanning the string multiple times to search/replace individual characters can be inefficient:

std::string escape(const std::string& src) {    std::stringstream dst;    for (char ch : src) {        switch (ch) {            case '&': dst << "&"; break;            case '\'': dst << "&apos;"; break;            case '"': dst << """; break;            case '<': dst << "<"; break;            case '>': dst << ">"; break;            default: dst << ch; break;        }    }    return dst.str();}

Note: I used a C++11 range-based for loop for convenience, but you can easily do the same thing with an iterator.


These types of functions should be standard and we should never have to rewrite them.If you are using VS, have a look at atlenc.hThis file is part of the VS installation.Inside the file there is a function called EscapeXML which is much more complete then any of the examples above.


As has been stated, it would be possible to write your own. For example:

#include <iostream>#include <string>#include <map>int main(){    std::string xml("a < > & ' \" string");    std::cout << xml << "\n";    // Characters to be transformed.    //    std::map<char, std::string> transformations;    transformations['&']  = std::string("&");    transformations['\''] = std::string("&apos;");    transformations['"']  = std::string(""");    transformations['>']  = std::string(">");    transformations['<']  = std::string("<");    // Build list of characters to be searched for.    //    std::string reserved_chars;    for (auto ti = transformations.begin(); ti != transformations.end(); ti++)    {        reserved_chars += ti->first;    }    size_t pos = 0;    while (std::string::npos != (pos = xml.find_first_of(reserved_chars, pos)))    {        xml.replace(pos, 1, transformations[xml[pos]]);        pos++;    }    std::cout << xml << "\n";    return 0;}

Output:

a < > & ' " stringa < > & &apos; " string

Add an entry into transformations to introduce new transformations.