我目前用TXMLDocument这个来生成xml文件(实现的参考例子应该是到处可见的。见如下:),xml文件中有一些数据是从数据库取的,也有一些是从外部获得变量经处理后的。
现在有一个新的需求是:
比如对生成的这个a.xml文件,它须是以UTF-8的文件编码格式的,这个应该如何实现。(注:不是[xmlDoc.Encoding]这个参数,而是整个a.xml的文件编码(用记事本打开时,选择另存为时可看到[编码]一项,目前是ansi,我希望它是utf-8。
生成xml参考的方法如下:------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
xmlDoc: IXMLDocument;
aNode, tmpNode: IXMLNode;
s: string;
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.Active := True;
xmlDoc.Version := '1.0';
xmlDoc.Encoding := 'utf-8';
aNode := xmlDoc.AddChild('breakfast_menu');
tmpNode := aNode.AddChild('food');
aNode := tmpNode.AddChild('name');
aNode.Text := 'Belgian Waffles';
aNode := tmpNode.AddChild('price');
aNode.Text := '$5.95';
aNode := tmpNode.AddChild('description');
aNode.Text := 'two of our ';
aNode := tmpNode.AddChild('calories');
aNode.Text := '650';
xmlDoc.SaveToFile('d:\test.xml');
finally
xmlDoc := nil;
end;
end;
现在有一个新的需求是:
比如对生成的这个a.xml文件,它须是以UTF-8的文件编码格式的,这个应该如何实现。(注:不是[xmlDoc.Encoding]这个参数,而是整个a.xml的文件编码(用记事本打开时,选择另存为时可看到[编码]一项,目前是ansi,我希望它是utf-8。
生成xml参考的方法如下:------------------------
procedure TForm1.Button1Click(Sender: TObject);
var
xmlDoc: IXMLDocument;
aNode, tmpNode: IXMLNode;
s: string;
begin
xmlDoc := TXMLDocument.Create(nil);
try
xmlDoc.Active := True;
xmlDoc.Version := '1.0';
xmlDoc.Encoding := 'utf-8';
aNode := xmlDoc.AddChild('breakfast_menu');
tmpNode := aNode.AddChild('food');
aNode := tmpNode.AddChild('name');
aNode.Text := 'Belgian Waffles';
aNode := tmpNode.AddChild('price');
aNode.Text := '$5.95';
aNode := tmpNode.AddChild('description');
aNode.Text := 'two of our ';
aNode := tmpNode.AddChild('calories');
aNode.Text := '650';
xmlDoc.SaveToFile('d:\test.xml');
finally
xmlDoc := nil;
end;
end;
var
wf: Array[0..2] of Char;
us: UTF8String;
f: TFileStream;
begin
Result:= false;
wf[0]:=#$EF;
wf[1]:=#$BB;
wf[2]:=#$BF;
f:= TFileStream.Create(filename, fmCreate);
try
f.Write(wf, 3);
us:=AnsiToUtf8(AnsiS);
f.Write(PChar(us)^, length(us));
Result := true;
finally
f.Free;
end;
end;//保存的时候,不要使用XmlDoc.SavetoFile,使用以上函数保存WriteUTF8String2File('d:\test.xml',XMLDoc.XML.Text);