簡體   English   中英

從stringstream轉換為string會刪除'='字符

[英]conversion from stringstream to string removes '=' characters

我正在將XML文件讀取到stringstream緩沖區中,以便使用RapidXML對其進行解析。 RapidXML僅解析XML節點的名稱,而不解析其屬性名稱或值。 經過一些實驗,我發現問題可能不是RapidXML,而是使用std :: string content(buffer.str());將stringstream緩沖區轉換為字符串。 在進行任何RapidXML處理之前 ,對XML解析非常重要的'='字符會轉換為''(空格字符)。

在下面的代碼中進行cout <<調用時,在控制台窗口中可以很明顯地看到字符替換,這是在RapidXML接觸到字符串之前。

我的代碼如下:

    #include <iostream>
    #include <fstream>
    #include <stdio.h>
    #include <conio.h>
    #include <string>
    #include <stdlib.h>
    #include <rapidxml.hpp>
    #include <vector>
    #include <sstream>

    using namespace std;
    using namespace rapidxml;

    //... main() and so forth, all works fine...

    ifstream file(names.at(i)); // names.at(i) works fine...
    //...
    file.read(fileData, fileSize); // works fine...
    //...
    // Create XML document object using RapidXML:
    xml_document<> doc;
    //...
    std::stringstream buffer;
    buffer << file.rdbuf();

    // This is where everything looks okay (i.e., '=' shows up properly):
    cout << "\n" << buffer.str() << "\n\nPress a key to continue...";
    getchar();
    file.close();
    std::string content(buffer.str());

    // This is where the '=' are replaced by ' ' (space characters):
    cout << "\n" << content << "\n\nPress a key to continue...";
    getchar();

    // Parse XML:
    doc.parse<0>(&content[0]);

    // Presumably the lack of '=' is preventing RapidXML from parsing attribute
    // names and values, which always follow '='...

在此先感謝您的幫助。

ps我遵循有關使用此技術的建議,以將整個XML文件讀入stringstream,將其轉換為字符串,然后從以下鏈接將字符串提供給RapidXML(感謝這些建議的提供者,對不起,我不能讓它們正常工作...):

自動化軟件的RapidXML迷你教程

...這種方法在其他很多地方都見過,我不會在這里列出。 似乎足夠明智。 我的錯誤似乎很獨特。 這可能是ASCII還是UNICODE問題?

我也從這里嘗試過代碼:

Thomas Whitton的示例將字符串緩沖區轉換為動態cstring

上面的代碼片段:

    // string to dynamic cstring
    std::vector<char> stringCopy(xml.length(), '\0');
    std::copy(xml.begin(), xml.end(), stringCopy.begin());
    char *cstr = &stringCopy[0];
    rapidxml::xml_document<> parsedFromFile;
    parsedFromFile.parse<0>(cstr);

...類似的RapidXML無法解析節點屬性名稱和值。 請注意,我沒有將字符向量stringCopy轉儲到控制台進行檢查,但是我遇到了相同的問題,需要檢查的是:

  1. 在RapidXML解析輸入給它進行分析的字符串之后,我看到正確解析的XML標簽名稱。
  2. 沒有正確解析的標記屬性名稱或值。 這些取決於要解析的字符串中顯示的'='字符。

如果仔細看, =字符可能不會被空格代替,而是零字節。 如果您在此處查看rapidxml文檔:

http://rapidxml.sourceforge.net/manual.html#namespacerapidxml_1differences

它特別指出修改了源文本。 這樣,它可以避免分配任何新字符串,而是使用指向原始源的指針。

這部分似乎正常工作,也許問題出在試圖讀取屬性的其余代碼?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM