c++string转xml格式
时间: 2023-07-04 16:28:56 浏览: 97
将 C++ 的字符串转换成 XML 格式同样需要进行一些特殊字符的转义,比如 `<` 转义为 `<`,`>` 转义为 `>`,`&` 转义为 `&`,`"` 转义为 `"`,`'` 转义为 `'` 等等。
以下是一个示例代码,将 C++ 的字符串转换成 XML 格式:
```c++
#include <iostream>
#include <string>
std::string escapeXml(const std::string& str) {
std::string result;
for (const auto& c : str) {
switch (c) {
case '<':
result += "<";
break;
case '>':
result += ">";
break;
case '&':
result += "&";
break;
case '\"':
result += """;
break;
case '\'':
result += "'";
break;
default:
result += c;
break;
}
}
return result;
}
int main() {
std::string str = "<root><element attribute=\"value\">Hello World</element></root>";
std::cout << escapeXml(str) << std::endl;
return 0;
}
```
运行这段代码,输出结果为:
```
<root><element attribute="value">Hello World</element></root>
```
可以看到,所有的 `<`、`>`、`&`、`"`、`'` 字符都被正确地转义了。
阅读全文
相关推荐

















