[英]How to save XmlTextReader strings inside a variable or vector in C++/CLI?
我目前正在從事一個項目,我必須在該項目中接收一個 XML 文件並對其中一個元素進行排序。
在實際進入排序部分之前,我必須解析 XML 文件,所以我使用XmlTextReader
,它運行良好。 但是,我需要將每個元素的屬性保存在變量或向量中,以便之后能夠執行排序(我的困難是嘗試存儲reader->Value
)。
這是我的代碼的一部分,有什么想法嗎?
PS你可以在下面的第二個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
是一個 .NET System::String
(一個 16 位 Unicode 字符串)。
您正在嘗試將其分配給std::string
(一個 8 位字符串)的std::vector
並將其存儲。
這兩種字符串類型彼此不直接兼容,這就是您遇到麻煩的原因。
您需要:
將您的myText
變量更改為System::String
,並將您的entries
向量更改為保存System::String
元素。
將System::String
數據轉換為std::string
。 如何做到這一點記錄在 MSDN: 如何:將 System::String 轉換為標准字符串。 另請參閱如何將 System::String^ 轉換為 std::string? 在 StackOverflow 上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.