How to make xml parser more clear

  • I have an xml file built in this way:

    @<?xml version="1.0" encoding="UTF-8"?>
    <header id="0">one</header>
    <header id="1">two</header>
    <header id="2">three</header>
    <header id="3">four</header>
    <header id="4">five</header>
    <header id="0">alfa</header>
    <header id="1">beta</header>
    <header id="2">gamma</header>
    <header id="3">delta</header>
    <header id="4">epsilon</header>

    And I'm trying to extrapolate the values ​​of the header tag: since we have two sets of header tags (Input and Output) the only working code that I managed to work for now is this:

    void MainWindow::readXmlFile() {
    QString target;
    QFile* file = new QFile("System/Settings.xml");
    /* If we can't open it, let's show an error message. /
    if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) return;
    QXmlStreamReader xmlReader(file);
    We'll parse the XML until we reach end of it./
    while(!xmlReader.atEnd() && !xmlReader.hasError()) {
    QXmlStreamReader::TokenType token = xmlReader.readNext();
    if(token == QXmlStreamReader::StartDocument) {
    If token is StartElement, we'll see if we can read it./
    if (token == 4) {
    if ( == "Input" || == "Output") {
    target =;
    if ((!(xmlReader.tokenType() == QXmlStreamReader::EndElement && == target))) {
    if (xmlReader.tokenType() == QXmlStreamReader::StartElement) {
    if ( == "header") {
    qDebug() << xmlReader.readElementText();
    Error handling. */
    if(xmlReader.hasError()) {

    Since this code seems very repetitive, especially from line 15 to 18, could you help me to make it a little cleaner?

    Thanks in advance

  • Lifetime Qt Champion


    You should have a look at the QXmlStream Bookmarks Example

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.