When I use QDomDocument with HTML content, it fails to set content if there is a <!doctype html> at the beginning of the document. But actually why?!
for example consider the following snippet of code:
QDomDocument doc;
QString content = "<!doctype html><html><body><a href='bar'>foo</a></body></html>";
qDebug() << doc.setContent(content,false,0,0);
QDomElement docElem = doc.documentElement();
QDomNode a = docElem.firstChild();
qDebug() << doc.childNodes().size() << docElem.childNodes().size();
nothing but a list of falses are the output of this code!
As @hank commented, you should use QDomDocument::elementsByTagName(const QString &tagname) to get the elements in the document with the name tagname . Then, iterate over the nodes to get each QDomNode . Finally, convert the QDomNode into a QDomElement .
The QDomDocument class represents the entire XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document's data.
HTML is HTML and XML is XML. Consequently, Qt XML is not able to parse HTML code correctly. To parse HTML files, consider using the Qt Webkit module instead of the Qt XML module. To include it in your project, you just have to add QT += webkit in your project file.
To parse your HTML datas, you will have to do something like this :
QString content = "<html><body><a href='bar'>foo</a></body></html>";
QWebPage webPage;
QWebFrame * frame = webPage.mainFrame();
frame->setHtml(content);
QWebElement htmlElement = frame->documentElement(); // Equivalent of the QDomElement
For further informations, see the Qt Webkit documentation and the QWebElement documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With