gpt4 book ai didi

c++ - 从字符串流到字符串的转换删除了 '=' 个字符

转载 作者:行者123 更新时间:2023-11-28 06:53:29 25 4
gpt4 key购买 nike

我正在将 XML 文件读入字符串流缓冲区,以便使用 RapidXML 对其进行解析。 RapidXML 仅解析 XML 节点的名称,但不解析它们的属性名称或值。经过一些实验,我发现问题不太可能出在 RapidXML 上,而是出在使用 std::string content(buffer.str()); 将 stringstream 缓冲区转换为字符串时。对 XML 解析非常重要的“=”字符被转换为“”(空格字符),任何 RapidXML 处理之前。

当在下面的代码中调用 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 '='...

预先感谢您的帮助。

附注我遵循了关于使用这种技术将整个 XML 文件读入字符串流,将其转换为字符串,然后从以下链接将字符串提供给 RapidXML 的建议(感谢这些建议的贡献者,抱歉我做不到他们还在工作......):

Automation Software's RapidXML mini-tutorial

...这个方法在很多地方都见过,这里就不一一列举了。似乎足够明智。我的错误似乎是独一无二的。这可能是 ASCII 与 UNICODE 的问题吗?

我也试过这里的代码:

Thomas Whitton's example converting a string buffer to a dynamic 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 解析节点属性名称和值的失败。请注意,我没有将字符 vector stringCopy 转储到控制台来检查它,但我遇到了同样的问题,需要审查的是:

  1. 在对提供给它进行分析的字符串进行 RapidXML 解析后,我看到了正确解析的 XML 标签名称。
  2. 没有正确解析的标记属性名称或值。这些取决于要解析的字符串中出现的“=”字符。

最佳答案

如果您仔细观察,= 字符可能不会被空格替换,而是零字节。如果您在此处查看 rapidxml 文档:

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

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

这部分似乎工作正常,也许问题出在您尝试读取属性的其余代码上?

关于c++ - 从字符串流到字符串的转换删除了 '=' 个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23462584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com