Delphi 与 XML 示例(直接利用IXMLDocument)

类别:Delphi 点击:0 评论:0 推荐:

(1)procedure TForm1.Button2Click(Sender: TObject);
var xmlDoc:IXMLDocument; aNode:IXMLNode;
begin
? xmlDoc := TXMLDocument.Create(nil);
? xmlDoc.Active := True;
? xmlDoc.Version := '1.0';
? xmlDoc.Encoding :='GB2312';
? try
??? //加入根结点
??? aNode:=xmlDoc.AddChild('bootDocNode');
??? //加入子结点
??? aNode:=aNode.AddChild('ChileNode1');
??? //设置接点属性
??? aNode.SetAttribute('ID', '22');
??? aNode.SetAttribute('Units', '元/m2');
??? aNode.SetAttribute('URL', 'http://URL.c');
??? //设置结点内容
??? aNode.Text := '结点内容';
??? //子结点添加子结点
??? aNode:=aNode.AddChild('Child_ChileNode1') ;
??? aNode.Text := 'Child_ChileNod内容';

??? memXML.Lines.Text := xmlDoc.XML.Text ;
? finally
??? xmlDoc := nil ;
? end;
end;

(2)procedure TForm1.Button3Click(Sender: TObject);? //从文件存取
var xmlDoc:IXMLDocument; rootNode,appSetN,aNode:IXMLNode;
begin
? xmlDoc := TXMLDocument.Create(nil);
? xmlDoc.Active := True;
? try
??? xmlDoc.LoadFromFile('D:\work\STUDY\XML\DOM\Web.config') ;
??? xmlDoc.Encoding :='GB2312';
??? rootNode := xmlDoc.ChildNodes.FindNode('configuration'); //root Node
??? appSetN := rootNode.ChildNodes.FindNode('appSettings');
??? if appSetN=nil then
??? begin
????? appSetN:=rootNode.AddChild('appSettings') ;
????? aNode:=appSetN.AddChild('add');
??????? aNode.SetAttribute('key', 'SNCode');
??????? aNode.SetAttribute('value', 'testCodeSN');
??????? aNode.SetAttribute('A编号','0101');
????? aNode:=appSetN.AddChild('add');
??????? aNode.SetAttribute('key', 'RegCode');
??????? aNode.SetAttribute('value', 'testREGCode');
??? end else
??? begin

??? end;

??? memXML.Lines.Text := xmlDoc.XML.Text ;
??? xmlDoc.SaveToFile('D:\work\STUDY\XML\DOM\Web.config') ;
? finally
??? xmlDoc := nil ;
? end;
end;

本文地址:http://com.8s8s.com/it/it4965.htm