2011-12-28 83 views
0

如何提取兩個標籤之間的CString?提取標籤之間的CString

<tag1>My Text</tag1> 

我不想計算開始和結束位置,然後使用中期,也許有另一種更簡單的方法使用STL?

+0

爲什麼在上帝的綠色地球上,你用MFC和CString解析HTML/XML? –

+0

有沒有理由不使用XML解析器庫? –

回答

0

聲明:以下想法是badshould not be used in production code。我假設你只是想快速測試一下。

使用正則表達式來匹配標籤。 Microsoft provides this in CAtlRegExp。如果您使用的是Visual Studio 2008或更新版本,則需要download ATL here。然後,只需提供myString下面的代碼:

#include "atlrx.h" 
CAtlRegExp<> regex; 
VERIFY(REPARSE_ERROR_OK == regex.Parse("<tag1>(.*)</tag1>")); 

CAtlREMatchContext<> mc; 
if (!regex.Match(myString, &mc)) { 
    // no match found 
} else { 
    // match(es) found 
    for (UINT nGroupIndex = 0; nGroupIndex < mc.m_uNumGroups; ++nGroupIndex) { 
     const CAtlREMatchContext<>::RECHAR* szStart = 0; 
     const CAtlREMatchContext<>::RECHAR* szEnd = 0; 
     mc.GetMatch(nGroupIndex, &szStart, &szEnd); 
     ptrdiff_t nLength = szEnd - szStart; 
     CString text(szStart, nLength); 
     // now do something with text 
    } 
} 

免責聲明2:你真的應該使用an XML parser library instead

+0

我需要僅提取幾個自定義元素,而不是整個html文件 –

相關問題