unit UCreateXML;//delphi 写xml文件方式
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, xmldom, XMLIntf, msxmldom, XMLDoc;
implementation
procedure CreateXML();
var
ixd: IXmlDocument;
RootNode: IXmlNode;
RangeNode: IXmlNode;
DataNode: IXmlNode;
FileDir,FileName:string;
begin
ixd := NewXmlDocument();
try
ixd.Encoding := 'UTF-8';
RootNode := ixd.AddChild('RootDatas');
RangeNode:= RootNode.AddChild('DataRange');
DataNode := RangeNode.AddChild('Name');
DataNode.Text := 'zhang san';
DataNode := RangeNode.AddChild('Sex');
DataNode.Text := 'male';
//node.Attributes['id'] := 1;
//node.Attributes['level'] := '1';
//node.Text := 'HAHA';
FileDir:=ExtractFilePath(ParamStr(0)) + 'XML\';
FileName:=FileDir+'aaa.xml';
ixd.SaveToFile(FileName);
finally
ixd := nil;
end;
end;
end.
unit UXmlRead; //XML读取方式
interface
uses Windows, xmldom, XMLIntf, msxmldom, XMLDoc, Classes, SysUtils, ActiveX,DB,
ADODB;
type
Rec_XMLData = record
Name, Sex : string;
end;
TSearchXMLFile = class(TObject)
private
protected
public
function GetAllFiles(Dir: string): TStrings;
end;
TGetXMLFileData = class(TObject)
private
public
function GetXMLData(FileName: string): Rec_XMLData;
end;
implementation
function TSearchXMLFile.GetAllFiles(Dir: string): TStrings;
var
FSearchRec: TSearchRec;
FileList: TStrings;
FindResult: Integer;
begin
if Dir[length(Dir)] <> '\' then
Dir := Dir + '\';
FileList := TStringList.Create;
FindResult := FindFirst(Dir + '*.xml', faAnyFile + faDirectory, FSearchRec);
try
while FindResult = 0 do
begin
FileList.Add(LowerCase(Dir + FSearchRec.Name));
FindResult := FindNext(FSearchRec);
end;
finally
FindClose(FSearchRec);
end;
Result := FileList;
end;
function TGetXMLFileData.GetXMLData(FileName: string): Rec_XMLData;
var
FXMLDoc: IXMLDocument;
XMLNode: IXMLNode;
RootNode: IXMLNode;
RangeNode: IXMLNode;
//DataNode: IXMLNode;
i: integer;
XMLData: Rec_XMLData;
begin
FXMLDoc := TXMLDocument.Create(nil);
FXMLDoc.LoadFromFile(fileName);
FXMLDoc.Active := true;
RootNode := FXMLDoc.DocumentElement;
// for i:=0 to XMLNode.ChildNodes.Count-1 do
i := 0;
begin
RangeNode:= RootNode.ChildNodes[I];
XMLData.SerialNo :=RangeNode.ChildValues['Name'];
XMLData.cphmcd := RangeNode.ChildValues['Sex'];
end;
result := XMLData;
FXMLDoc.Active:=False;
end;
end.