delphi 如何将XML格式的字符串导入ClientDataSet中
下面我写了一个公用函数:
uses XMLDoc, XMLIntf,msxml,msxmldom;
function XMLToDataSet(strXML:WideString):TClientDataSet;
var
myDataSet:TClientDataSet;
s:string;
xdoc : IXMLDOMDocument;
xdn :IXMLDOMNode;
xdns :IXMLDOMNodeList;
i,j:integer;
begin
s:='<?xml version="1.0" encoding="gb2312"?> <!--文档版本信息, 注释格式同HTML-->'
+'<data>'
+'<row>'
+'<id>11</id><name>AAA</name><sex>男9</sex><age>24</age>'
+'</row>'
+'<row>'
+'<id>12</id><name>BBB</name><sex>女8</sex><age>25</age>'
+'</row>'
+'<row>'
+'<id>13</id><name>CCC</name><sex>女7</sex><age>26</age>'
+'</row>'
+'<row>'
+'<id>4</id><name>DDD</name><sex>男6</sex><age>28</age>'
+'</row>'
+'</data>';
//上面的格式就是传递参数strXML:WideString的格式,必须用row节点
myDataSet := TClientDataSet.Create(nil);
xdoc:=CreateDOMDocument();
xdoc.loadXML(StrXML);
//xdoc.load('c:\test.xml');
s:='';
xdn:=xdoc.documentElement;
xdns:=xdoc.selectNodes('//row');
try
begin
for i:=0 to xdns.item[0].childNodes.length-1 do
begin
myDataSet.FieldDefs.Add(xdns.item[0].childNodes[i].nodeName,ftstring,1000);
end;
myDataSet.CreateDataSet; //建立
myDataSet.Active;
for i:=0 to xdns.length-1 do
begin
myDataSet.Append;
for j:=0 to xdns.item[i].childNodes.length-1 do
begin
myDataSet.FieldValues[xdns.item[i].childNodes[j].nodeName]:=xdns.item[i].childNodes[j].text;
end;
myDataSet.Post;
end;
end;
except
on Ex:Exception do
//ShowMessage(Ex.Message);
myDataSet:=nil;
end;
result:=myDataSet;
end;