数据集数据转换为XML
function ReplaceString(AString: string): string;
begin
Result := StringReplace(AString, '&', '&', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
end;
function DataSetToXml(ADataSet: TDataSet; Indent: Integer): string;
var
i: Integer;
Indent1, Indent2: string;
temp: string;
begin
Indent1 := Format('%*s', [Indent * 2, ' ']);
Indent2 := Indent1 + ' ';
Result := EmptyStr;
ADataSet.First;
while not ADataSet.Eof do
begin
Result := Result + Format('%s<%s>'#13#10, [Indent1, 'Record']);
for i := 0 to ADataSet.FieldCount - 1 do
if ADataSet.Fields[i].DataType in [ftString .. ftAutoInc, ftMemo,
ftWideString] then
begin
temp := ReplaceString(ADataSet.Fields[i].AsString);
Result := Result + Format('%2:s<%0:s>%1:s</%0:s>'#13#10,
[ADataSet.Fields[i].FieldName, temp, Indent2])
end;
Result := Result + Format('%s</%s>'#13#10, [Indent1, 'Record']);
ADataSet.Next;
end;
end;
function GenerateXml(ADataSet: TDataSet): string;
begin
Result := Format
('<?xml version="1.0" encoding="gb2312"?>'#13#10'<Records>'#13#10'%s</Records>',
[DataSetToXml(ADataSet, 1)]);
end;
转换后生成的XML文件内容类似:
<?xml version="1.0" encoding="gb2312"?>
<Records>
<Record>
<userid>1</userid>
<username>李三</username>
</Record>
<Record>
<userid>2</userid>
<username>王五</username>
</Record>
</Records>
解析XML内容生成数据集的数据,本例中使用TXMLDocument控件
procedure TForm1.Button1Click(Sender: TObject);
var
rn,pn,sn:IXMLNode;
i,j:Integer;
begin
ClientDataSet1.EmptyDataSet;
rn:=x.DocumentElement;
for i := 0 to rn.ChildNodes.Count-1 do begin
pn := rn.ChildNodes[i];
ClientDataSet1.Append;
for j := 0 to pn.ChildNodes.Count-1 do begin
sn:=pn.ChildNodes[j];
ClientDataSet1.FindField(sn.NodeName).Text :=sn.NodeValue;
end;
ClientDataSet1.Post;
end;
end;