Alireza Mirian
Alireza Mirian

Reputation: 6672

QDomDocument fails to set content of an HTML document with <!doctype> tag

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!

Upvotes: 6

Views: 3539

Answers (2)

air-dex
air-dex

Reputation: 4180

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.

Upvotes: 7

Troubadour
Troubadour

Reputation: 13421

Use the optional arguments to setContent to find out what the parsing error is. It could be something as simple as the case of "doctype".

Upvotes: 0

Related Questions