htmlc++qtqt4qtxml

QDomDocument get element by class


I have several divs in an HTML file with different classes, like this:

<div class='A'>...</div>
<div class='B'>...</div>
<div class='C'>...</div>

I have a Qt (4.7) program where I need to be able to get a certain div out of this based on the class. I need to use QDomDocument in this program. I know from the documentation that that class has a function elementById(), but I can't get that to work with classes, just ids. This isn't a HTML file a made or anything, so I don't have any control over whether it's class or id. Is there a way to do this that I'm missing? Thanks!


Solution

  • It looks like you need something like this along the lines:

    main.cpp

    #include <QDomDocument>
    #include <QDomElement>
    #include <QDomNodeList>
    #include <QDomAttr>
    
    #include <QFile>
    #include <QDebug>
    
    int main()
    {
        QDomDocument doc("mydocument");
        QFile file("mydocument.xml");
        if (!file.open(QIODevice::ReadOnly))
            return 1;
    
        if (!doc.setContent(&file)) {
            file.close();
            return 1;
        }
        file.close();
    
        QDomNodeList divNodeList = doc.elementsByTagName("div");
    
        for (int i = 0; i < divNodeList.size(); ++i) {
            QDomElement domElement = divNodeList.at(i).toElement();
            QDomAttr attribute = domElement.attributeNode("class");
            qDebug() << "Attribute value" << attribute.value();
            if (attribute.value() == "A")
                qDebug() << "Found A";
        }
    
        return 0;
    }
    

    Output

    g++ -Wall -fPIC -I/usr/include/qt -I/usr/include/qt/QtCore -I/usr/include/qt/QtXml -lQt5Xml -lQt5Core main.cpp && ./a.out