QString.replace不起作用



我正在尝试处理QString中的HTML数据。数据有编码的HTML标记,例如"<"等。我想将这些标记转换为适当的符号。

我尝试了很多方法,但似乎都不起作用,这表明我错过了一些非常简单的东西。

以下是代码(修改以修复早期评论中报告的拼写错误):

QString theData = "&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Arial'; font-size:20pt; font-weight:400; font-style:normal;&quot;&gt;
&lt;table border=&quot;0&quot; style=&quot;-qt-table-type: root; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px;&quot;&gt;
&lt;tr&gt;
&lt;td style=&quot;border: none;&quot;&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:14pt; color:#4cb8ff;&quot;&gt;This is text on the second page. This page contains a embedded image,&lt;/span&gt;&lt;/p&gt;
&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-size:14pt; color:#4cb8ff;&quot;&gt;and audio.&lt;/span&gt;&lt;/p&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;";
QString t2 = theData.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "'");

但是,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 &lt;QtCore&gt;"

如果您只想转换html实体,我使用以下函数,作为QString::toHtmlEscaped():的补充

QString fromHtmlEscaped(QString html) {
  html.replace("&quot;", """, Qt::CaseInsensitive);
  html.replace("&gt;", ">", Qt::CaseInsensitive);
  html.replace("&lt;", "<", Qt::CaseInsensitive); 
  html.replace("&amp;", "&", Qt::CaseInsensitive);
  return html;
}

在所有情况下,它都应该保持str == fromHtmlEscaped(str.toHtmlEscaped())

最新更新