I am currently working on a project in which I have to receive a XML file and sort one of the elements.
Before actually getting to the sorting part, I have to parse the XML file, so I am using XmlTextReader
, which is working well. However, I need to save each element's attribute in a variable or in a vector to be able to perform the sort afterwards (my struggle is with trying to store the reader->Value
).
Here is part of my code, any ideas?
P.S. You can see my struggle in the second switch
case below, I kept receiving errors on all those attempts.
#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();
CodePudding user response:
reader->Value
is a .NET System::String
(a 16bit Unicode string).
You are trying to assign it to, and store it in a std::vector
of, std::string
(an 8bit string).
Those two string types are not directly compatible with each other, which is why you are having troubles.
You need to either:
change your
myText
variable toSystem::String
, and yourentries
vector to holdSystem::String
elements.convert the
System::String
data tostd::string
. How to do that is documented on MSDN: How to: Convert System::String to Standard String.