為了搞定HTML,這幾天在學著用
Tidylib,終于搞明白了,喜滋滋地合并到代碼中一測試,傻眼了--字符集問題。。。
Tidylib的輸入流似乎只支持const char*, 因此不的不將std::wstring從‘寬字節’轉換為‘多字節。轉換了幾次,時好時壞,搞到半夜才發現自己所用的幾個測試HTML頁面都各種包含著不同的字符集,于是字符集問題就出來了,也搞死我了~最后一咬牙,一跺腳,老子我不轉了,都用‘RAW’數據好了,‘寬’到‘多’直接用UTF8了。。。于是就有了下面的代碼。
int CHtmlTidyObject::Tidy(const std::wstring &input, std::wstring &output)


{
int codepage = CP_UTF8;//54936;//CP_UTF8;

int ret = -1;

TidyDoc tdoc = tidyCreate();
if(tidyOptSetBool(tdoc, TidyMark, no) != yes)
return -1;
if(tidyOptSetInt(tdoc, TidyDoctypeMode, TidyDoctypeOmit) != yes)
return -1;
if(tidyOptSetBool(tdoc, TidyHideComments, yes) != yes)
return -1;
if(tidyOptSetInt(tdoc, TidyWrapLen, 0) != yes)
return -1;
//if(tidyOptSetBool(tdoc, TidyMakeClean, yes) != yes)//css
// return -1;
if(tidyOptSetBool(tdoc, TidyUpperCaseTags, yes) != yes)
return -1;
if(tidyOptSetBool(tdoc, TidyHtmlOut, yes) != yes)
return -1;
if(tidySetCharEncoding(tdoc, "raw") != 0)
return -1;
if(tidyOptSetBool(tdoc, TidyShowWarnings, no) != yes)
return -1;
if(tidyOptSetInt(tdoc, TidyShowErrors, 0) != yes)
return -1;

if(tidyOptSetBool(tdoc, TidyForceOutput, yes) != yes)
return -1;

int sz = WideCharToMultiByte(codepage, 0, input.c_str(), input.size(), NULL, 0, NULL, NULL);
if(sz == -1)
return -1;
char* buf = new char[sz + 1];
sz = WideCharToMultiByte(codepage, 0, input.c_str(), input.size(), buf, sz, NULL, NULL);
if(tidyParseString(tdoc, buf) >= 0)

{
//TidyBuffer errbuf = {0};
//tidySetErrorBuffer( tdoc, &errbuf );
if(tidyCleanAndRepair(tdoc) >= 0)

{
//tidyRunDiagnostics( tdoc );


TidyBuffer outbuf =
{ 0 };
if(tidySaveBuffer(tdoc, &outbuf) >= 0)

{
//std::cout << "OUTPUT->\n" << outbuf.bp << std::endl;
int wsz = MultiByteToWideChar(codepage, 0, (const char*)outbuf.bp, outbuf.size, NULL, 0);
wchar_t* wbuf = new wchar_t[wsz + 1];
wsz = MultiByteToWideChar(codepage, 0, (const char*)outbuf.bp, outbuf.size, wbuf, wsz);
output = wbuf;
delete [] wbuf;
ret = 0;
}
tidyBufFree(&outbuf);
}
//std::cout << "ERROR->\n" << errbuf.bp << std::endl;
//tidyBufFree(&errbuf);
}

delete [] buf;

tidyRelease(tdoc);

return ret;
}
感覺還有問題,但經過Tidy處理,TinyHtmlParser確實能解析原來解不開的HTML數據了,就先放著吧,測試看看先~唉,HTML從頭到尾都是最影響LingosHook的部分,早知道應該多好好找找穩定的Parser,自己造的輪子對路面要求太高了。。。