Skip to content

Instantly share code, notes, and snippets.

@killwing
Created November 20, 2012 07:48
Show Gist options
  • Save killwing/4116631 to your computer and use it in GitHub Desktop.
Save killwing/4116631 to your computer and use it in GitHub Desktop.
[escapeXml] escape XML special chars
#include <iostream>
#include <string>
using namespace std;
std::string escapeXml(const std::string& s) {
std::string ret;
std::string::size_type i = 0;
std::string::size_type pos = 0;
for (; i != s.size(); ++i) {
std::string rep;
if (s[i] == '<') {
rep = "&lt;";
} else if (s[i] == '>') {
rep = "&gt;";
} else if (s[i] == '&') {
rep = "&amp;";
} else {
continue;
}
ret += s.substr(pos, i - pos) + rep;
pos = i + 1;
}
ret += s.substr(pos);
return ret;
}
std::string unescapeXml(const std::string& s) {
std::string ret;
std::string::size_type i = 0;
std::string::size_type pos = 0;
while (i < s.size()) {
std::string rep;
if (s[i] == '&') {
if (s.substr(i, 4) == "&lt;") {
ret += s.substr(pos, i - pos) + "<";
i += 4;
pos = i;
} else if (s.substr(i, 4) == "&gt;") {
ret += s.substr(pos, i - pos) + ">";
i += 4;
pos = i;
} else if (s.substr(i, 5) == "&amp;") {
ret += s.substr(pos, i - pos) + "&";
i += 5;
pos = i;
} else {
++i;
}
} else {
++i;
}
}
ret += s.substr(pos);
return ret;
}
int main() {
std::string ss("[hello xml] < '500' && [xml hello] > '100'");
cout << escapeXml(ss) << endl;
std::string xx("[hello xml] &lt; '500' &amp;&amp; [xml hello] &gt; '100'");
cout << unescapeXml(xx) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment