1、采用正则表达式先匹配带的标签,
2、通过正则表达式匹配context。
3、后面可以处理context的内容。
注意:目前:context 只能为 英文字符 、数字 、_ 三种字符,如果需要支持不同的字符,可以通过修改正则表达式达到目标。
#include "stdafx.h"
#include<iostream>
#include<regex>
#include<map>
using namespace std;
wstring XmlCompressByReplace( std::wstring inputXmlStr , std::map<std::wstring,std::wstring> markMap)
{
std::wregex regTag(L"</?[^>]+/?>"); //匹配<context>
std::wregex regTagContext(L"[0-9a-zA-Z-_]+"); // 匹配context
std::wstring result;
int pos = 0;
while ((pos = inputXmlStr.find(L">")) != -1 )
{
std::wsmatch matchResult;
wstring resultstr= inputXmlStr.substr(0, pos + 1);
inputXmlStr = inputXmlStr.substr(pos + 1);
std::wstring matchResultStr;
if ( std::regex_search(resultstr, matchResult, regTag) )
{
matchResultStr = matchResult.str();
}
else
{
cout << "匹配错误!" << endl;//写日志
return L"";
}
std::wstring matchResultContextStr;
if ( std::regex_search(matchResultStr, matchResult, regTagContext) )
{
matchResultContextStr = matchResult.str();
}
else
{
cout << "匹配错误!" << endl; //写日志
return L"";
}
int start = matchResultStr.find(matchResultContextStr);
wstring tempStr = matchResultStr;
if (markMap[matchResultContextStr]==L"")
{
cout << "标签不存在!" << endl; //写日志
return L"";
}
matchResultStr.replace( start, matchResultContextStr.length(), markMap[matchResultContextStr] );
start = resultstr.find(tempStr);
resultstr.replace(start, tempStr.length(), matchResultStr);
result += resultstr;
}
return result;
}
int main()
{
std::wstring text = L"<aa12>sd</aa12><bbbb>sdsd</bbbb><cccc/>";
map<wstring, wstring> mak;
mak[L"aa12"] = L"A";
mak[L"bbbb"] = L"B";
mak[L"cccc"] = L"C";
wstring ss = XmlCompressByReplace(text, mak);
wcout << ss << endl;
return 0;
}