2011-04-19 130 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";