QDomDocument无法使用<!doctype>设置HTML文档的内容。标签 [英] QDomDocument fails to set content of an HTML document with <!doctype> tag

查看:134
本文介绍了QDomDocument无法使用<!doctype>设置HTML文档的内容。标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将 QDomDocument 与HTML内容一起使用时,如果存在<!doctype html> 在文档开头。但是为什么呢?例如,以
为例,请考虑以下代码段:

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();

什么都没有,但有 false 的列表

nothing but a list of falses are the output of this code!

推荐答案

HTML是HTML,XML是XML。因此, Qt XML 无法正确解析HTML代码。要解析HTML文件,请考虑使用 Qt Webkit 模块而不是 Qt XML 模块。要将其包含在项目中,只需在项目文件中添加 QT + = webkit

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.

到解析HTML数据,您将必须执行以下操作:

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

有关更多信息,请参见 Qt Webkit文档 QWebElement文档

For further informations, see the Qt Webkit documentation and the QWebElement documentation.

这篇关于QDomDocument无法使用&lt;!doctype&gt;设置HTML文档的内容。标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆