delphi 读取xml

2024-12-27 04:44:41
推荐回答(1个)
回答1:

XML文档内容如下:
-------------------------------------------------------------------------------------------------------





-------------------------------------------------------------------------------------------------------
使用TNativeXML解析方法如下:

procedure ReadXML(CDSMainTemp, CDSMain: TClientDataSet);
var
XMLDoc: TNativeXML;
RootNode, MainNode, LineNode, LineNode1, SubLineNode: TXMLNode;
kkk, kk, mingxi1, mingxi2, MainNum, LineNum, Line1Num, SubLineNum, RootNum, RowNum, k, i, j: integer;
job, ss, S: string;
begin
XMLDoc := TNativeXML.Create;
XMLDoc.LoadFromFile('C:\Documents and Settings\Test\桌面\ERP 1.0\ERP.xml');
RootNode := XMLDoc.Root; //ERP
MainNode := RootNode.Nodes[1]; //Main
LineNode := MainNode.Nodes[1]; //Line
MainNum := RootNode.NodeCount; //主表的行数
RowNum := MainNode.AttributeCount; //主表的字段数目
LineNum := MainNode.NodeCount; //主表的明细行数
// job := RootNode.Nodes[0].Name;

/// ShowMessage(job);
CDSMainTemp.EmptyDataSet;
CDSMain.EmptyDataSet;
for k := 0 to MainNum - 1 do //ERP节点下面的第二层主表行数循环
begin
if RootNode.Nodes[k].Name = 'Job' then
begin
RowNum := RootNode.Nodes[0].AttributeCount;
CDSMainTemp.Append;
for j := 0 to RowNum - 1 do //主表字段数目循环
begin //读取XML文档中一行节点名和节点值并赋值到数据集
for i := 0 to CDSMainTemp.Fields.Count - 1 do //循环匹配数据集字段赋值
begin
CDSMainTemp.FieldByName(RootNode.Nodes[0].AttributeName[i]).AsString := RootNode.Nodes[0].AttributeValue[i]; //MainNode.Nodes[j].AttributeValue[j];
end;
end;
CDSMainTemp.Post;
end
else if RootNode.Nodes[k].Name = 'Main' then
begin
RowNum := RootNode.Nodes[1].AttributeCount;
CDSMain.Append;
for j := 0 to RowNum - 1 do //主表字段数目循环
begin //读取XML文档中一行节点名和节点值并赋值到数据集
for i := 0 to CDSMain.Fields.Count - 1 do //循环匹配数据集字段赋值
begin
CDSMain.FieldByName(RootNode.Nodes[k].AttributeName[j]).AsString := RootNode.Nodes[k].AttributeValue[j]; //MainNode.Nodes[j].AttributeValue[j];
end;
end;
CDSMain.Post;
end;
end;
end;