Background
The following XML snippet contains configuration parameters for our application in key-value pair manner. (Despite using INI files for such purpose may be better, I have to use XML files.)
<configuration>
<parameter id="serial_port_name">ttyS0</parameter>
<parameter id="serial_port_baud_rate">9600</parameter>
<parameter id="check_period">1000</parameter>
<parameter id="locale">hu_HU</parameter>
<!-- ... -->
</configuration>
I would like to read the configuration parameters and store them inside a QHash<QString, QString>
object with minimal overhead, therefore I've chosen the QXmlStreamReader
for iterating through XML elements.
Current code
The toConfigurationMap()
method of the following class
iterates through the elements of XML file and when a <configuration>
element is found, starts another iteration on the level of <parameter>
elements to parse them.
class ConfigurationReader {
public:
explicit ConfigurationReader(QFile& input) : reader(&input) {
}
QHash<QString, QString> toConfigurationMap() {
QHash<QString, QString> output;
for(auto token = reader.tokenType(); !reader.atEnd();
token = reader.readNext()) {
if(token != QXmlStreamReader::StartElement ||
reader.name() != "configuration")
continue;
while(reader.readNextStartElement()) {
if(reader.name() == "parameter") {
QString id = reader.attributes().value("id").toString();
output.insert(id, reader.readElementText());
}
else {
reader.skipCurrentElement();
}
}
}
return output;
}
private:
QXmlStreamReader reader;
};
Goals
I would like to reduce the complexity of the code above, by somehow take apart the nested loops. In order to the toConfigurationMap()
method be more cleaner, I would like to communicate to the reader that "it parses the parameters for each configuration elements" through the code.