zoukankan      html  css  js  c++  java
  • Delphi 中的 XMLDocument 类详解(15) 创建与保存 xml

    unit Unit1;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, xmldom, XMLIntf, StdCtrls, msxmldom, XMLDoc;
    
    type
      TForm1 = class(TForm)
        XMLDocument1: TXMLDocument;
        Button1: TButton;
        Button2: TButton;
        procedure Button1Click(Sender: TObject);
        procedure Button2Click(Sender: TObject);
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.dfm}
    
    //利用 XML 属性创建 xml 文件
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      XMLDocument1.XML.Clear;
      XMLDocument1.XML.Add('');
      XMLDocument1.XML.Add('<科室名单 备注="测试">');
      XMLDocument1.XML.Add('<人员 职务="科长" 备注="正局级">');
      XMLDocument1.XML.Add('<姓名>张三');
      XMLDocument1.XML.Add('<性别>男');
      XMLDocument1.XML.Add('<年龄>34');
      XMLDocument1.XML.Add('');
      XMLDocument1.XML.Add('');
    
      {查看}
      ShowMessage(XMLDocument1.XML.Text);
    
      {保存}
      XMLDocument1.Active := True;
      XMLDocument1.SaveToFile('c:\temp\1.xml');
    end;
    
    
    //创建 xml 文件的标准方法
    procedure TForm1.Button2Click(Sender: TObject);
    var
      pNode,cNode: IXMLNode; {定义两个节点: 父节点、子节点}
    begin
      XMLDocument1.XML.Clear;
      XMLDocument1.Active := True;                {必须先激活}
      XMLDocument1.Version := '1.0';              {设置版本}
      XMLDocument1.Encoding := 'GB2312';          {设置语言}
    
      pNode := XMLDocument1.AddChild('科室名单'); {添加的第一个节点是根节点, 现在的 pNode 是根节点}
      pNode.SetAttribute('备注', '测试');         {为根节点设置属性}
    
      pNode := pNode.AddChild('人员');            {为根节点添加子节点, 现在的 pNode 是 "人员" 节点}
      pNode.SetAttribute('职务', '科长');         {设置属性}
      pNode.SetAttribute('备注', '正局级');
    
      cNode := pNode.AddChild('姓名');  {为 pNode 添加子节点, 返回值 cNode 指向了新添加的节点}
      cNode.Text := '张三';
    
      cNode := pNode.AddChild('性别');
      cNode.Text := '男';
    
      cNode := pNode.AddChild('年龄');
      cNode.Text := '34';
    
      {查看}
      ShowMessage(XMLDocument1.XML.Text);
    
      {保存}
      XMLDocument1.SaveToFile('c:\temp\2.xml');
    end;
    
    end.
    
  • 相关阅读:
    【转载】利用bat批处理做启动mongodb脚本
    【转载】Spring中@Component与@Bean的区别
    IDEA使用@Data注解,类调用get、set方法标红的解决办法
    Navicat premium工具转储数据表的结构时,datatime字段报错
    【转】Redis 基础操作和命令
    简单的js购物车结算
    文件下载
    图片报错,显示默认图片
    php 数组操作
    thinkphp5分页样式及参数保留
  • 原文地址:https://www.cnblogs.com/del/p/1027315.html
Copyright © 2011-2022 走看看