Dor*_*hen 8 c++ xml escaping special-characters
我搜索网络很多,并没有找到用他们的转义序列替换xml特殊字符的c ++函数?有这样的事吗?
我知道以下内容:
Special Character Escape Sequence Purpose
& & Ampersand sign
' ' Single quote
" " Double quote
> > Greater than
< < Less than
Run Code Online (Sandbox Code Playgroud)
还有更多吗?怎么样写十六进制值如0×00,这也是一个问题吗?
Fer*_*cio 11
编写自己的文件很简单,但是多次扫描字符串以搜索/替换单个字符可能效率低下:
std::string escape(const std::string& src) {
std::stringstream dst;
for (char ch : src) {
switch (ch) {
case '&': dst << "&"; break;
case '\'': dst << "'"; break;
case '"': dst << """; break;
case '<': dst << "<"; break;
case '>': dst << ">"; break;
default: dst << ch; break;
}
}
return dst.str();
}
Run Code Online (Sandbox Code Playgroud)
注意:为方便起见,我使用了基于C++ 11范围的for循环,但您可以使用迭代器轻松完成相同的操作.
小智 7
这些类型的函数应该是标准的,我们永远不应该重写它们.如果您使用的是VS,请查看atlenc.h此文件是VS安装的一部分.在文件内部有一个名为EscapeXML的函数,它比上面的任何示例都要完整得多.
如前所述,可以自己编写.对于例如:
#include <iostream>
#include <string>
#include <map>
int main()
{
std::string xml("a < > & ' \" string");
std::cout << xml << "\n";
// Characters to be transformed.
//
std::map<char, std::string> transformations;
transformations['&'] = std::string("&");
transformations['\''] = std::string("'");
transformations['"'] = std::string(""");
transformations['>'] = std::string(">");
transformations['<'] = std::string("<");
// Build list of characters to be searched for.
//
std::string reserved_chars;
for (auto ti = transformations.begin(); ti != transformations.end(); ti++)
{
reserved_chars += ti->first;
}
size_t pos = 0;
while (std::string::npos != (pos = xml.find_first_of(reserved_chars, pos)))
{
xml.replace(pos, 1, transformations[xml[pos]]);
pos++;
}
std::cout << xml << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
a < > & ' " string
a < > & ' " string
Run Code Online (Sandbox Code Playgroud)
添加一个条目transformations以引入新的转换.