打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
回复 "Globe" 关于 XML 编码转换的问题

问题来源:http://www.cnblogs.com/del/archive/2011/03/24/1994029.html#2059114

Globe 同学有这样的 XML 文件:
<?xml version="1.0" encoding="gb2312"?><root><friend name="&#x5341;&#x5E74;"></friend><friend name="&#x66FE;&#x7D93;&#x5954;&#x653E;&#x904E;&#x30FE;&#x20;"></friend><friend name="&#46028;&#50500;&#50752; &#45208;&#49244; &#45320; "></friend></root>

其中包含中文、韩文,并且有些是十六进制、有些是十进制,真实的内容应该是:
<?xml version="1.0" encoding="GB2312"?><root><friend name="十年"></friend><friend name="曾經奔放過ヾ "></friend><friend name="??? ?? ? "></friend></root>

下面是把它打开并另存为标准的 UTF-8 格式 XML 的代码(使用了 DelphiXE 最新的正则表达式组件):

unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls, RegularExpressions;type  TForm1 = class(TForm)    Button1: TButton;    procedure Button1Click(Sender: TObject);  private    function MyMatchEvaluator(const Match: TMatch): stringpublic  end;var  Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);const  pattern = '&#x?[0-9A-Fa-f]{1,5};';var  List: TStringList;  reg: TRegEx;  path,tmpName: string;begin  with TOpenDialog.Create(nil) do begin    Execute;    path := FileName;    Free;  endif path = '' then Exit;  List := TStringList.Create;  List.LoadFromFile(path);  List.Text := StringReplace(List.Text, 'GB2312', 'UTF-8', [rfIgnoreCase]);  reg := TRegEx.Create(pattern, [roCompiled]);  List.Text := reg.Replace(List.Text, MyMatchEvaluator);  tmpName := ExtractFileName(path);  path := StringReplace(path, tmpName, 'UTF8_' + tmpName, [rfIgnoreCase]);  Text := path;  List.SaveToFile(path, TEncoding.UTF8);  List.Free;end;function TForm1.MyMatchEvaluator(const Match: TMatch): string;begin  Result := Match.Groups[1].Value;  if Match.Value[3] = 'x' then Result := '$' + Result;  Result := WideChar(StrToInt(Result));end;end.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Delphi版的Base64转换函数
碧水航工作室
转delphi过程函数传递参数的几种方式
delphi读写XML
delphi一句话帮助
delphi Restful:客户端实现的四种方式及其比较
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服