从字符串流到字符串的转换会删除'='字符

conversion from stringstream to string removes '=' characters

本文关键字:字符串 字符 删除 转换      更新时间:2023-10-16

我正在读取XML文件到字符串流缓冲区,以便使用RapidXML解析它。RapidXML只解析XML节点的名称,而不解析它们的属性名称或值。经过一些实验后,我发现问题不太可能与RapidXML有关,而是与使用std::string内容(buffer.str());将stringstream缓冲区转换为字符串有关。对于XML解析非常重要的'='字符被转换为' '(空格字符),优先于任何RapidXML处理

当执行命令<<时,字符替换在控制台窗口中很明显。调用在下面的代码中进行,这是在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() << "nnPress a key to continue...";
    getchar();
    file.close();
    std::string content(buffer.str());
    // This is where the '=' are replaced by ' ' (space characters):
    cout << "n" << content << "nnPress 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 '='...

提前感谢您的帮助。

注。我按照建议使用这种技术将整个XML文件读取为字符串流,将其转换为字符串,然后从以下链接将字符串提供给RapidXML(感谢这些建议的贡献者,抱歉我还不能使它们工作…):

自动化软件的RapidXML迷你教程

…这种方法在很多地方都见过,我就不一一列举了。看起来很明智。我的错误似乎是独一无二的。这可能是ASCII与UNICODE的问题吗?

我也试过从这里写代码:

Thomas Whitton将字符串缓冲区转换为动态cstring的示例

上面的代码片段:

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

…使用类似的RapidXML解析节点属性名称和值失败。请注意,我没有将字符向量stringCopy转储到控制台以检查它,但我遇到了同样的问题,供审查是:

  1. 我看到正确解析的XML标签的名称后,快速XML解析的字符串提供给它进行分析。
  2. 没有正确解析的标签属性名或值。这些依赖于要解析的字符串中出现的'='字符。

如果你仔细观察=字符可能不是被空格取代,而是零字节。如果你看一下这里的rapidxml文档:

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

它特别声明它修改源文本。这样可以避免分配任何新的字符串,而是使用指向原始源的指针。

这部分似乎工作正常,也许问题是你的代码的其余部分,试图读取属性?