Delphi使用NativeXml访问XML文件

时间:2023-03-09 01:56:41
Delphi使用NativeXml访问XML文件

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);