#include "stdafx.h"
#include <string>
#include <stdarg.h>
#include <memory>
#include <iostream>
#include <map>
using namespace std;
namespace {
string StringReplace(const string& str_src, const string& from, const string& to) {
if (str_src.empty()
|| from.empty()
|| to.empty())
{
return str_src;
}
string str_dst;
string str_src_tmp = str_src;
size_t from_size = from.size();
size_t to_size = to.size();
// 循环处理未处理字符串
for (size_t pos = str_src_tmp.find(from); string::npos != pos; pos = str_src_tmp.find(from))
{
str_src_tmp.replace(pos, from_size, to); // 替换from到to
str_dst += str_src_tmp.substr(0, from_size + pos); // 获取已处理字符串
str_src_tmp = str_src_tmp.substr(from_size + pos); // 获取未处理字符串
}
// 拼接剩余字符串
str_dst += str_src_tmp;
return str_dst;
}
}
/**
* XML文档中,如果内容包含某些特殊字符会导致XML文件无法解析,需要对内容做转义处理。
*/
string StringEscapeForXML(const string& str_src) {
if (str_src.empty()) {
return str_src;
}
string str_dst = str_src;
static map<char, string> map_special = {
{ '&', "&" },
{ '\'', "'" },
{ '"', """ },
{ '<', ">" },
{ '>', "<" }
};
size_t size = str_dst.size();
for (size_t pos = 0; pos < size;) {
char c = str_dst.at(pos);
auto iter_c = map_special.find(c);
if (map_special.end() != iter_c)
{
str_dst.replace(pos, 1, iter_c->second);
pos += iter_c->second.size();
size += iter_c->second.size() - 1;
continue;
}
++pos;
}
return str_dst;
}
int main() {
string str_xml = "|abc|&|'|\"|<|>|";
string str_xml_escape = StringEscapeForXML(str_xml);
getchar();
return 0;
}
XML特殊字符转义
最新推荐文章于 2024-02-24 12:51:49 发布