加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:23:18 所属栏目:百科 来源:网络整理
导读:问题来源: http://www.cnblogs.com/del/archive/2011/03/24/1994029.html#2059114 Globe 同学有这样的 XML 文件: lt;?xml version=quot;1.0quot; encoding=quot;gb2312quot;?gt; lt;Rootgt; lt;friend name=quot;amp;#x5341;amp;#x5E74;quot;gt;lt;/friend

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

Globe 同学有这样的 XML 文件:
<?xml version="1.0" encoding="gb2312"?> <Root> <friend name="十年"></friend> <friend name="曾經奔放過ヾ "></friend> <friend name="돌아와 나쁜 너 "></friend> </Root>

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

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

unit Unit1;

interface

uses
  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): string;
  public
  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;
  end;
  if 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读