Created
November 20, 2012 07:48
-
-
Save killwing/4116631 to your computer and use it in GitHub Desktop.
[escapeXml] escape XML special chars
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 = "<"; | |
} else if (s[i] == '>') { | |
rep = ">"; | |
} else if (s[i] == '&') { | |
rep = "&"; | |
} 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) == "<") { | |
ret += s.substr(pos, i - pos) + "<"; | |
i += 4; | |
pos = i; | |
} else if (s.substr(i, 4) == ">") { | |
ret += s.substr(pos, i - pos) + ">"; | |
i += 4; | |
pos = i; | |
} else if (s.substr(i, 5) == "&") { | |
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] < '500' && [xml hello] > '100'"); | |
cout << unescapeXml(xx) << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment