我试图将xml存储到字符串中.这在C++中真的可行吗?我收到了一个反复的错误:
error: parse error before string constant
Run Code Online (Sandbox Code Playgroud)
在尝试编写一行代码时如下:
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> ";
Run Code Online (Sandbox Code Playgroud)
除了将它保存到文件之外还有其他任何方式..?我不能直接将它存储到一个字符串中..请帮帮我朋友...
您必须转义"字符和换行符.
就像是:
std::string str = "bryan says: \"quoted text\" :) \n\
other line";
Run Code Online (Sandbox Code Playgroud)
这会给你以下字符串:
bryan says: "quoted text" :)
other line
Run Code Online (Sandbox Code Playgroud)
另请注意,如果要在字符串中存储特定的utf-8或Latin1字符,则必须相应地设置源文件的编码.
在大多数情况下,通常更容易单独存储xml文件,并在以后将其作为程序的资源包含在内.这将使您的代码更具可读性,并且可以根据需要简化对xml结构的修改.
在这种情况下也要注意,因为std::string没有对这些字符的特定支持,length()可能会产生不必要的结果.