Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I search the web alot and didn't find c++ function that replace xml Special Character with their escape sequence? Is there something like this?

I know about the following:

Special Character   Escape Sequence Purpose  
&                   &           Ampersand sign 
'                   '          Single quote 
"                   "          Double quote
>                   >            Greater than 
<                   &lt;            Less than

is there more? what about writing hexadecimal value like 0×00, Is this also a problem?

like image 263
Dor Cohen Avatar asked Mar 28 '12 08:03

Dor Cohen


1 Answers

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 << "&amp;"; break;
            case '\'': dst << "&apos;"; break;
            case '"': dst << "&quot;"; break;
            case '<': dst << "&lt;"; break;
            case '>': dst << "&gt;"; 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.

like image 75
Ferruccio Avatar answered Sep 20 '22 12:09

Ferruccio