How do I run XPath queries in QT?


How do I run an XPath query in QT?

I need to sort out certain tags with specific values in a certain attribute. The QXmlQuery documentation is anything but legible.

The schema I'm parsing is the Rhythmbox DB format:

<rhythmdb version="1.6">
  <entry type="ignore">
  <entry type="song">
    <genre>Foobared Music</genre>
    <album>The Great big Bar</album>

This is your basic XML Schema which has a collection of structured entries. My intention was to filter out the entries with the type 'ignore'.

8/17/2009 3:34:57 PM

Accepted Answer

The relevant documentation is at:

The solution I came to was to use QXmlQuery to generate an XML file then parse it again using QDomDocument.

    QXmlQuery query;
    QXmlQuery entries;
    QString res;
    QDomDocument rhythmdb;

     * Try and open the Rhythmbox DB. An API call which tells us where
     * the file is would be nice.
    QFile db(QDir::homePath() + "/.gnome2/rhythmbox/rhythmdb.xml");
    if ( ! db.exists()) {
        db.setFileName(QDir::homePath() + "/.local/share/rhythmbox/rhythmdb.xml");
        if ( ! db.exists())

    if (! | QIODevice::Text))

     * Use QXmlQuery to execute and XPath query. Check the version to
     * make sure.
    if ( ! query.isValid())


     * Parse the result as an XML file. These shennanigans actually
     * reduce the load time from a minute to a matter of seconds.
    rhythmdb.setContent("" + res + "");
    m_entryNodes = rhythmdb.elementsByTagName("entry");

    for (int i = 0; i < m_entryNodes.count(); i++) {
        QDomNode n =;
        QString location = n.firstChildElement("location").text();

        m_mTracksByLocation[location] = n;

    qDebug() << rhythmdb.doctype().name();
    qDebug() << "RhythmboxTrackModel: m_entryNodes size is" << m_entryNodes.size();

In case anyone is wondering, this is my code taken from a recent branch of the Mixxx project, specifically the features_looping branch.

The things I dislike about this solution are:

  • Parsing the XML twice
  • Concatenating the result with a starting and ending tag.
11/16/2013 9:12:06 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow