1

I'm trying to write some very simple functions to escape and unescape strings with respect to XML escape sequences. These are the escape sequences I care about:

unescaped escaped
' '
" "
& &
< &lt;
> &gt;

I've already managed to write the escape_XML() function, but I'm unsure what the best way to write the inverse function, unescape_XML(). Is it possible to match on the current string prefix while iterating? I do not have access to any libraries besides the C++ standard library.

Here is a complete example with my code so far:

#include <iostream>

std::string escape_XML(const std::string &input) {
    std::string output;
    for (char chr : input) {
        if (chr == '"') output += "&quot;";
        else if (chr == '&') output += "&amp;";
        else if (chr == '<') output += "&lt;";
        else if (chr == '>') output += "&gt;";
        else if (chr == '\'') output += "&apos;";
        else output += chr;
    }
    return output;
}

std::string unescape_XML(const std::string &input) {
    std::string output;
    /* for (char chr : input) {
            if (prefix == "&quot;") ...
            else if (prefix == "&amp;") ...
            else if (prefix == "&lt;") ...
            else if (prefix == "&gt;") ...
            else if (prefix == "&apos;") ...
            else output += chr;
    } */
    return output;
}

int main() {
    std::string input{
            "\" <-> &quot;\n"
            "& <-> &amp;\n"
            "< <-> &lt;\n"
            "> <-> &gt;\n"
            "\' <-> &apos;\n"
    };
    const std::string escaped = escape_XML(input);
    std::cout << "ESCAPED" << std::endl;
    std::cout << escaped;
    const std::string unescaped = unescape_XML(escaped);
    std::cout << "UNESCAPED" << std::endl;
    std::cout << unescaped;
    std::cout << std::flush;
}
dumbo
  • 71
  • 2
  • Does this answer your question? [How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?](https://stackoverflow.com/questions/1878001/how-do-i-check-if-a-c-stdstring-starts-with-a-certain-string-and-convert-a) – 273K May 09 '21 at 15:49

0 Answers0