2016-04-01 15 views
0

QStringに保持されたHTMLデータを処理しようとしています。データには、エンコードされたHTMLタグがあります。 "<"など。私はこれらを適切な記号に変換したい。QString.replaceが動作しない

私は多くのアプローチを試みてきましたが、どれもうまくいかないようです。これは本当に簡単なものが欠けていることを示唆しています。 T2の値が、しかし置き換え後theData同じである

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;", "'"); 

:ここ

コード(以前のコメントによって報告されたタイプミスを修正する修正)です。

+0

"t1..replace" < - これは有効なC++構文のようには見えません。 – MrEricSir

答えて

0

あなたのコードにはt1の定義はありません。データを意味すると思います(ダブルドットなし)。 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"); 

しかし/アンエスケープの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;" 

あなたが唯一の私がQString::toHtmlEscaped()と相補的な、次の関数を使用して、HTMLエンティティを変換したい場合:

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())を保持する必要があります。

+0

置換の順序が重要な場合は、最後にアンパサンドを置換する必要があります。私は返信に関数を編集した、コメントを削除すること自由に感じる。一般的に言えば、質問/回答の不足を示すコメントは、それぞれ質問/回答を修正または修正することによって対処する必要があります。 –