Best Way to Read XML Tags w/o Specifying Tag's Name



  • I just started Qt development yesterday. I'm trying to find a way to read an XML file, without specifying the tags' names (we have a variety of tags, and we cannot enumerate them all; some may/may not be children of a specific tag). I looked into qxmlstreamreader, but that still requires you to specify the tags' names.

    How should I proceed? And thanks in advance.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    What exactly do you want to do with the content of that file ?



  • Hi,
    Creating a very "abstract" xml parser is not easy and it's quite error-prone. You have to know some (or at least one) parent or common tag names in order to have a starting point for any deeper "abstract" parsing. Basically, you have to move the parser step by step checking everything in the way. For example, you could use a simple function as an entry point for the following function when you meet a specific tag:

    void XmlReader::readFragment()
    {
        Q_ASSERT(m_reader->isStartElement()); //Make sure the xmlreader is at an opening tag
        const QString p = m_reader->qualifiedName().toString(); // From now on, you will work with this opening tag
        
    	//Do what you want, for example handle attributes and their values
    	for (auto i = 0; i < m_reader->attributes().count(); ++i) {
            ...
        }
        m_reader->readNext(); //Move on
    	...
    	
    	//Do everything manually like this
    	if (m_reader->isCharacters) {
    		...
    	} else if (m_reader->isEndElement()) {
    		...
    	}
    	
    	//or like this
            //Eventually, you have to check for the closing current tag, exit the function,
            //and return the control to the "entry point" function
    	while (!m_reader->isEndElement() && !m_reader->qualifiedName().toString() == p) { 
    		... //Do your work
                    m_reader->readNext();
    	}
    	
    }
    

    However, with this approach, things can get extremely complicated if there are nested tags, for example:

    <p>
       <note>
            <p>...</p>
       </note>
    </p>
    

    Maybe it would be easier to subclass QXmlStreamReader but it would help to provide some sample xml data and more info on what exactly you want to do.



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