xml字符串编码

项目中要用到,在C++中又没有的函数可供调用, 还是自己动手写吧


 

 // testcreatesrandkey.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;


void XmlEncode(const string& strSrc, string& strDest)
{
 for(int i = 0; i < strSrc.length(); i++)
 {
  char c = strSrc[i];
  switch(c)
  {
  case '&' :
   strDest.append("&amp;");
   break;
  case '<' :
   strDest.append("&lt;");
   break;
  case '>' :
   strDest.append("&gt;");
   break;
  case '"' :
   strDest.append("&quot;");
   break;
  case '/'' :
   strDest.append("&apos;");
   break;
  default :
   {
    char p[2];
                p[0] = c;
    p[1] = 0;
    strDest.append(p);
    break;
   }
  }
 }
}

void XmlDecode(const string& strSrc, string& strDest)
{
 for(int i = 0; i < strSrc.length(); i++)
 {
  char c = strSrc[i];
  switch(c)
  {
  case '&':
   {
    if((strSrc[i + 1] == 'l') && (strSrc[i+ 2])== 't' && (strSrc[i + 3]) == ';')
    {
     strDest.append("<");
     i += 3;
    }
    else if((strSrc[i + 1] == 'g') && (strSrc[i+ 2])== 't' && (strSrc[i + 3]) == ';')
    {
     strDest.append(">");
     i += 3;
    }
    else if((strSrc[i + 1] == 'a') && (strSrc[i+ 2])== 'm' && (strSrc[i + 3]) == 'p' && (strSrc[i + 4]) == ';')
    {
     strDest.append("&");
     i += 4;
    }
    else if(strSrc[i + 1] == 'q' && strSrc[i + 2] == 'u' && strSrc[i + 3] == 'o' && strSrc[i + 4] == 't' && strSrc[i + 5] == ';')
    {
     strDest.append("/"");
     i += 5;
    }
    else if(strSrc[i + 1] == 'a' && strSrc[i + 2] == 'p' && strSrc[i + 3] == 'o' && strSrc[i + 4] == 's' && strSrc[i + 5] == ';')
    {
     strDest.append("'");
     i += 5;
    }
    break;
    
   }
  default :
   {
    char p[2];
                p[0] = c;
    p[1] = 0;
    strDest.append(p);
    break;
   }
   
  }
 } 
}

int main(int argc, char* argv[])
{
/*
string strTest;
for(int i = 0 ; i < 128; i++)
{
//Sleep(1);
char p[2];
p[0] = static_cast<unsigned char>(i);
p[1] = 0;
strTest = strTest + p;
cout << strTest.c_str() << endl;
}
 */
 string strTest = "T//_q.t.gj*<;.rO^-}JY7";
 string strEncode;
 
 cout << strTest.c_str() <<endl;
 XmlEncode(strTest, strEncode);

 cout << strEncode.c_str() <<endl;

 strEncode = strTest;
 string strSrc;
 XmlDecode(strEncode, strSrc);

 cout<< strSrc.c_str() << endl;

 cout << strSrc.length() <<endl;
 return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值