View Full Version : XML, read file, string to enum.....

14th April 2014, 11:08
Hello everybody,
i have an xml file which i read during start-up and write when the programm is quit.
The dataset is read into a qmap during parsing. Two parameters i read through the process are form typ enum.

///*! Enum for xxx names*/
typedef enum {
x1 = 0, /***/
x3, /***/
x8, /***/
undefined_xxNames /***/
QString getEnumxxNames(EnumxxNames element);

QString graphicsEnum::getEnumxxNames(EnumxxNames element)
case x1:
return QString("x1");
case x3:
return QString("x3");
case x8:
return QString("x8");
return QString::number(element);

in xml parser

qDebug()<<readItem(xx,getStringXMLItem(Properties),getString XMLItemProperties(xxName));
Note readItem gives back a Qstring -->
reads out x1, x3,x8

if i want to conert that back to the enum using static cast

qDebug()<<getEnumxxNames(static_cast<EnumxxNames>(readItem(xx,getStringXMLItem(Properties),getStrin gXMLItemProperties(xxName)));
reads out x8

why is that...what is wrong here....
Is there a other way to get this done ?

14th April 2014, 11:34
You cannot cast a string to an integer or enum.
Just like for the conversion in the other direction you'll need a function that understands the enum and its string representation.
Something like

EnumxxNames getEnumValue(const QString &element)
if (element == "x1") return x1;
if (element == "x3") return x3;

return static_cast<EnumxxNames>(element.toInt()); // actually should check the result of toInt before casting

Alternatively you can do the string -> value mapping with a map or hash that uses the string representation as the keys and the respective enum value as the values.