2011-04-19 118 views
0

我尝试到XML存储到string.Is在C真的可行++我得到一个copile错误:存储XML为字符串

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> "; 

有没有比它保存到文件等任何其他方式..我不能直接存储到一个字符串..Please就帮我的朋友...

+0

,取决于您所使用XML做什么,你可能也想看看了Xerces库: http://xerces.apache.org/xerces-c/ – forsvarir 2011-04-19 07:45:48

回答

5

你有什么打算?逃脱"个字符和newl ine字符。

喜欢的东西:

std::string str = "bryan says: \"quoted text\" :) \n\ 
other line"; 

,这将给你下面的字符串:

bryan says: "quoted text" :) 
other line 

还要注意的是,如果你要存储在字符串中的特定UTF-8或Latin1的字符编码的源文件必须相应地设置。

在大多数情况下,通常更容易分开存储xml文件,并稍后将其作为程序资源包含在其中。这将使您的代码更具可读性,并且可以在需要时轻松修改xml结构。

在这种情况下还要小心,因为std::string对这些字符没有特别的支持,length()可能会给出不想要的结果。

0

您必须使用反斜杠(\)来清除所有"字符。您也必须使用\来跳过换行符。

你的代码是这样:

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> " ; 
+3

这是不完整的:换行符也需要转义。 – ereOn 2011-04-19 07:51:17

1

正如已经指出的那样,你需要逃跑报价,并使用"\n"新线。我想补充一点,相邻的字符串字面串联,这样你就可以向下突破字符串转换成很好地格式化行:

std::string xmlString = 
    "<animalList dnPrefix=\"String\">\n" 
    " <node>\n"           
    " <animal ID=\"xxxxxxxx\">\n" 
    // ...    
    " </node>\n" 
    "</animalList>\n";