Delphi使用NativeXml訪問XML檔案
1.建立XML檔案
var Doc: TNativeXml;//宣告上下文物件
var filepath:string;//檔案路徑
DOC:=TNativeXml.CreateName('root');
Doc.EncodingString:='gb2312';
DOC.XmlFormat:=xfReadable;
DOC.SaveToFile(filepath);
2.建立新節點
//先在根節點下建立一個節點名為userInfo的節點,然後給該節點寫一個屬性為loginname,屬性值為ceshiyong
DOC.Root.NodeNew('userInfo').WriteAttributeString('loginname','ceshiyong');
3.更新節點
with Doc.Root.NodeByName('sysconfig').NodeByName('netconfig').NodeByName('webserviceconfig') do
begin
WriteString('serverurl',model.serverurl);
WriteString('serverport',model.serverport);
end;
DOC.SaveToFile(filepath);
4.在父節點下建立子節點
//在根節點下查詢屬性loginname='ceshiyong'節點,並在該節點下建立節點名為baseinfo節點
with Doc.Root.NodeByAttributeValue('userInfo','loginname','ceshiyong').NodeNew('baseinfo') do
begin
WriteString('id','');
WriteString('name','');
WriteString('loginname','');
WriteString('shenfen','');
WriteString('nickname','');
WriteString('email','');
WriteString('qq','');
WriteString('mobile','');
WriteString('officephone','');
WriteString('HomePhone','');
WriteString('Address','');
WriteString('birthday','');
WriteString('sex','');
end;
5.節點查詢(查詢多個節點)
var AList: TXmlNodeList;
ALIST:=TXmlNodeList.Create;
Doc.Root.FindNodes('userInfo',AList);