将XML存储为字符串

storing xml to a string

本文关键字:字符串 存储 XML      更新时间:2023-10-16

我试图将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";