Question

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!

Was it helpful?

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

OTHER TIPS

Try getting the div elements first, by doing this:

QDomDocument l_doc;
l_doc.setContent( "here goes your html" );
QDomNodeList l_divs( l_doc.elementsByTagName( "div" ) );

then you can retrieve the attributes values with this:

for ( int i = 0 ; i < l_divs.size() ; ++i ) {
    QDomElement l_div( l_divs.at( i ).toElement() );
    QString l_class( l_div.attribute( "class" ) );
    qDebug() << "class attribute:" << l_class;
}

I suggest you reconsider the use of QDomDocument and try QWebView and QWebElement instead. With these classes you can use CSS selectors, what would make this (and others) tasks much easier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top