我正在尝试处理QString中的HTML数据。数据有编码的HTML标记,例如"<"等。我想将这些标记转换为适当的符号。
我尝试了很多方法,但似乎都不起作用,这表明我错过了一些非常简单的东西。
以下是代码(修改以修复早期评论中报告的拼写错误):
QString theData = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Arial'; font-size:20pt; font-weight:400; font-style:normal;">
<table border="0" style="-qt-table-type: root; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;">
<tr>
<td style="border: none;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:14pt; color:#4cb8ff;">This is text on the second page. This page contains a embedded image,</span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:14pt; color:#4cb8ff;">and audio.</span></p></td></tr></table></body></html>";
QString t2 = theData.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", "'");
但是,t2的值与替换后的数据相同。
您的代码中没有t1的定义,我想您指的是Data(没有双点)。QString::replace函数更改字符串的值并返回其引用。
QString s = "abc";
s.replace("a", "z").replace("b", "z");
// s = "zzc";
// if you don't want to alter s
QString s = "abc";
QString t = s;
t.replace("a", "z").replace("b", "z");
但是有更好的方法来转义/unescape html字符串:
// html -> plain text
QTextDocument doc;
doc.setHtml(theData);
QString t2 = doc.toPlainText();
// plain text -> html
QString plainText = "#include <QtCore>"
QString htmlText = plainText.toHtmlEscaped();
// htmlText == "#include <QtCore>"
如果您只想转换html实体,我使用以下函数,作为QString::toHtmlEscaped()
:的补充
QString fromHtmlEscaped(QString html) {
html.replace(""", """, Qt::CaseInsensitive);
html.replace(">", ">", Qt::CaseInsensitive);
html.replace("<", "<", Qt::CaseInsensitive);
html.replace("&", "&", Qt::CaseInsensitive);
return html;
}
在所有情况下,它都应该保持str == fromHtmlEscaped(str.toHtmlEscaped())
。