如何保存XmlTextReader字符串内的变量或向量在c++ /CLI?



我目前正在处理一个项目,我必须接收一个XML文件并对其中一个元素进行排序。

在实际进入排序部分之前,我必须解析XML文件,所以我使用XmlTextReader,它工作得很好。但是,我需要将每个元素的属性保存在变量或向量中,以便能够在之后执行排序(我的挣扎是试图存储reader->Value)。

这是我的一部分代码,有什么想法吗?

注:你可以看到我的挣扎在第二个switch的情况下,我一直收到错误的所有这些尝试。

#include "pch.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <tchar.h>
#using <System.Windows.Forms.dll>
#using <mscorlib.dll>
using namespace std;
using namespace System;
using namespace System::Xml;
int main() {
string myText = "";
vector<string> entries = { "DeTal" };
entries.insert(entries.end(), "Fulano");//test purposes

XmlTextReader^ reader = gcnew XmlTextReader("C:\Users...");
while (reader->Read())
{
switch (reader->NodeType)
{
case XmlNodeType::Element: // The node is an element.
Console::Write("<{0}", reader->ReadToFollowing("TITLE"));
while (reader->MoveToNextAttribute()) {// Read the attributes.
Console::Write(" {0}='{1}'", reader->GetAttribute("TITLE"));
}
Console::WriteLine(">");
break;
case XmlNodeType::Text: //Display the text in each element.
Console::WriteLine(reader->Value); //reads the actual element content
//entries.insert(entries.end(), reader->Value);
//entries.push_back(reader->Value);
//myText = Console::WriteLine(reader->Value);
//myText = Console::WriteLine(reader->ReadString());
//myText = reader->Value;
break;
case XmlNodeType::EndElement: //Display the end of the element.
Console::Write("</{0}", reader->Name);
Console::WriteLine(">");
break;
}
}
cout << "nPress enter to start sort: ";
Console::ReadLine();

reader->Value是一个。netSystem::String(一个16位Unicode字符串)。

您正在尝试将其分配给std::vector,并将其存储在std::string(一个8位字符串)中。

这两种字符串类型彼此不直接兼容,这就是您遇到问题的原因。

你需要:

  • myText变量更改为System::String,并将entries向量更改为System::String元素。

  • System::String数据转换为std::string。如何做到这一点在MSDN上有文档:如何将System::String转换为标准字符串。参见如何将System::String^转换为std:: String ?StackOverflow。

最新更新