2

我有带有 unicode 符号的 html 标记:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML xmlns:o = "urn:schemas-microsoft-com:office:office"><HEAD>
<META content="text/html; charset=windows-1251" http-equiv=Content-Type>
<META name=GENERATOR content="MSHTML 9.00.8112.16441"></HEAD>
<BODY>
<P>&#968;</P></BODY></HTML>

&#968;我使用 IHTMLTxtRange.pasteHTML 插入的符号。当我使用 HTMLDocument2.body.innerHTML 时,我想得到<P>&#968;</P>,但不是 Unicode 字符串函数的字符串表示形式,而是返回 Unicode BSTR,其中&#968;(ψ) 是 Unicode 字符 $03C8

4

1 回答 1

0

另一种解决方法

function GetInnerHTMLFromBody(const ADocument: IHTMLDOCUMENT2): AnsiString;
var
  ms: TMemoryStream;
  startBody: integer;
  stopBody: integer;
const
  bodyTag = '<BODY>';
  closedBodyTag = '</BODY>';
begin
  Result := '';
  if ADocument <> nil then
  begin
    ms := TMemoryStream.Create;
    try
      Succeeded((ADocument as IPersistStreamInit).Save(
        TStreamAdapter.Create(ms, soReference) as IStream, true));
      ms.Seek(0, soFromBeginning);
      SetLength(Result, ms.size);
      ms.ReadBuffer(Result[1], ms.size);
      // better to use regexpr
      startBody := AnsiPos(bodyTag, Result) + Length(bodyTag);
      stopBody := AnsiPos(closedBodyTag, Result);
      Result := Copy(Result, startBody, stopBody - startBody);
    finally
      ms.Free;
    end;
  end;
end;

但是,此方法仅适用于 ANSI 编码的 html 文档。如果 Unicode 编码你需要做一个额外的从 Unicode 到 AnsiString 的转换:

if SameText(Utf8ToAnsi(UTF8Encode(HTMLDocument2.charset)),'unicode') then
...
于 2012-04-05T19:18:08.533 回答