computer 잡다/이것저것

HTML Entity decoder for C++ and std::wstring

omnimook 2006. 6. 15. 22:52
C++용  HTML Entity decoder를 찾았는데, 잘 찾아지지가 않았다.

성능이고 버그고 뭐고 급하게 짰다. 혹시나 다른 사람에게 도움이 될까 올려본다. 개선사항 환영.

그리고, 표준이 안 맞을수도 :-)

// -- source code --

#ifndef HTML_ENTITY_DECODER_H_2328_
#define HTML_ENTITY_DECODER_H_2328_
#include <string>
#include <map>

class HTMLEntityDecoder
{
public:
   HTMLEntityDecoder()
   {
       m_charMap.insert(TCharMap::value_type(L"quot",L"\""));
       m_charMap.insert(TCharMap::value_type(L"amp",L"&"));
       m_charMap.insert(TCharMap::value_type(L"lt",L"<"));
       m_charMap.insert(TCharMap::value_type(L"gt",L">"));
   }
   std::wstring decode(const std::wstring& str)
   {
       std::wstring dStr = str;
       std::wstring::size_type nextPos = 0;
       while( nextPos < dStr.size() )
       {
           std::wstring::size_type spos = dStr.find(L"&",nextPos);
          
           if( spos == std::wstring::npos )
           {
               break;
           }
          
           std::wstring::size_type epos = dStr.find(L";",spos+1);

           if( epos == std::wstring::npos )
           {
               break;
           }

           std::wstring token = dStr.substr(spos+1,epos-1-(spos+1)+1);
           std::wstring::size_type cpos = token.find(L"#");
           if ( cpos == std::wstring::npos )
           {
               //string
               std::wstring ch = token.substr(0,token.size());
               TCharMap::iterator it = m_charMap.find(ch);
               if ( it != m_charMap.end() ) {
                 dStr.replace(spos,epos-spos+1,it->second);
               }
           }
           else
           {
               //number
              std::wstring number =token.substr(cpos+1,token.size()-1);
               wchar_t c = _wtoi(number.c_str());
               std::wstring s;
               s = s + c;
               dStr.replace(spos,epos-spos+1,s);
           }

           nextPos = spos+1;
       }
       return dStr;
   }
private:
   typedef std::map< std::wstring, std::wstring > TCharMap;
   TCharMap m_charMap;

};
#endif //HTML_ENTITY_DECODER_H_2328_

// -- sample
/*
std::wstring str = L"HaHaHoHo&#39;s log HaHaHo&#039;s log  메롱&#92;메롱 &quot;쿨럭&quot; ";
HTMLEntityDecoder decoder;
std::wstring dstr = decoder.decode(str);
*/