将XML存储为字符串
storing xml to a string
我试图将xml存储为字符串。这在c++中真的可行吗?我得到一个编译错误:
error: parse error before string constant
,当试图写一行代码,如:
string xmlString = "<animalList dnPrefix="String">
<node>
<animal ID="xxxxxxxx">
<Status>managed</Status>
<Type>ENB</Type>
<Subtype>0</Subtype>
<Version1>0.0</Version1>
<Version2>0.0</Version2>
<Name>ChicagoWest5678</Name>
<LocalName>ChicagoWest5678</LocalName>
</animal>
<animal ID ="yyyyyy">
<Status>managed</Status>
<Type>ENB</Type>
<Subtype>0</Subtype>
<Version1>0.0</Version1>
<Version2>0.0</Version2>
<Name>ChicagoWest5678</Name>
<LocalName>ChicagoWest5678</LocalName>
</animal>
</node>
</animalList> ";
除了保存到文件中,还有其他方法吗?我不能直接把它存储到一个字符串中吗?
必须转义"
字符和换行符。
类似:
std::string str = "bryan says: "quoted text" :) n
other line";
它会给你以下字符串:
bryan says: "quoted text" :)
other line
还请注意,如果您打算在字符串中存储特定的utf-8或Latin1字符,则必须相应地设置源文件的编码。
在大多数情况下,单独存储xml文件并稍后将其作为程序的资源包含通常更容易。这将使您的代码更具可读性,并且在需要时简化对xml结构的修改。
在这种情况下也要注意,因为std::string
没有对这些字符的特定支持,length()
可能会产生不想要的结果。
您必须用反斜杠()转义所有
"
字符。您还必须使用转义换行字符。
你的代码看起来像:
std::string xmlString = "<animalList dnPrefix="String">
<node>
<animal ID="xxxxxxxx">
<Status>managed</Status>
<Type>ENB</Type>
<Subtype>0</Subtype>
<Version1>0.0</Version1>
<Version2>0.0</Version2> <Name>ChicagoWest5678</Name>
<LocalName>ChicagoWest5678</LocalName>
</animal>
<animal ID ="yyyyyy">
<Status>managed</Status>
<Type>ENB</Type>
<Subtype>0</Subtype>
<Version1>0.0</Version1>
<Version2>0.0</Version2> <Name>ChicagoWest5678</Name>
<LocalName>ChicagoWest5678</LocalName>
</animal>
</node>
</animalList> " ;
如前所述,您需要转义引号,并对新行使用"n"
。我将添加相邻的字符串字面量连接,因此您可以将字符串分解为格式良好的行:
std::string xmlString =
"<animalList dnPrefix="String">n"
" <node>n"
" <animal ID="xxxxxxxx">n"
// ...
" </node>n"
"</animalList>n";
相关文章:
- 将字符串存储在c++中的稳定内存中
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 将字符串存储到文件下一行的变量中
- 将字符串存储在 constexpr 结构中
- 将字符串存储为十六进制而不进行转换
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将非数字字符串存储为二进制整数
- 将 C++ 字符串存储到 char* 向量中
- C++无法将对齐的字符串存储在字符串变量中并打印出来
- 短(ASCII,每个字符 7 位)字符串存储和C++中的比较优化
- 我无法将 Excel 中的输入字符串存储为二维字符串
- 如何将此字符串存储为不同的变量
- C 将字符串存储到类中
- C :占用更多内存,将单个字符作为char或字符串存储
- 排序通过字符串C 存储在向量的对象
- 如何将可变长度字符串存储在C/C 中
- 将字符串存储在无符号长整型的向量中
- 如何使用模板解码将来自 YAML::Node 的字符串存储在类中
- 将字符串存储到数组中
- C++-将用逗号分隔的用户输入字符串存储到向量中