国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

由數(shù)據(jù)庫(kù)數(shù)據(jù)生成XML的方法(有源碼)

2019-11-18 18:26:30
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友
 

PRocedure DatasetToxml(Dataset: TDataset; FileName: string);

unit DS2XML;

interface

uses
  Classes, DB;

procedure DatasetToXML(Dataset: TDataset; FileName: string);

implementation

uses
  SysUtils;

var
  SourceBuffer: PChar;

procedure WriteString(Stream: TFileStream; s: string);
begin
  StrPCopy(SourceBuffer, s);
  Stream.Write(SourceBuffer[0], StrLen(SourceBuffer));
end;

procedure WriteFileBegin(Stream: TFileStream; Dataset: TDataset);

  function XMLFieldType(fld: TField): string;
  begin
    case fld.DataType of
      ftString: Result := '"string" WIDTH="' + IntToStr(fld.Size) + '"';
      ftSmallint: Result := '"i4"'; //??
      ftInteger: Result := '"i4"';
      ftWord: Result := '"i4"'; //??
      ftBoolean: Result := '"boolean"';
      ftAutoInc: Result := '"i4" SUBTYPE="Autoinc"';
      ftFloat: Result := '"r8"';
      ftCurrency: Result := '"r8" SUBTYPE="Money"';
      ftBCD: Result := '"r8"'; //??
      ftDate: Result := '"date"';
      ftTime: Result := '"time"'; //??
      ftDateTime: Result := '"datetime"';
    else
    end;
    if fld.Required then
      Result := Result + ' required="true"';
    if fld.Readonly then
      Result := Result + ' readonly="true"';
  end;

var
  i: Integer;
begin
  WriteString(Stream, '  ' +
                      '');
  WriteString(Stream, '');

  {write th metadata}
  with Dataset do
    for i := 0 to FieldCount-1 do
    begin
      WriteString(Stream, '');
    end;
  WriteString(Stream, '');
  WriteString(Stream, '');
  WriteString(Stream, '');
end;

procedure WriteFileEnd(Stream: TFileStream);
begin
  WriteString(Stream, '');
end;

procedure WriteRowStart(Stream: TFileStream; IsAddedTitle: Boolean);
begin
  if not IsAddedTitle then
    WriteString(Stream, 'end;

procedure WriteRowEnd(Stream: TFileStream; IsAddedTitle: Boolean);
begin
  if not IsAddedTitle then
    WriteString(Stream, '/>');
end;

procedure WriteData(Stream: TFileStream; fld: TField; AString: ShortString);
begin
  if Assigned(fld) and (AString <> '') then
    WriteString(Stream, ' ' + fld.FieldName + '="' + AString + '"');
end;

function GetFieldStr(Field: TField): string;

  function GetDig(i, j: Word): string;
  begin
    Result := IntToStr(i);
    while (Length(Result) < j) do
      Result := '0' + Result;
  end;

var Hour, Min, Sec, MSec: Word;
begin
  case Field.DataType of
    ftBoolean: Result := UpperCase(Field.AsString);
    ftDate: Result := FormatDateTime('yyyymmdd', Field.AsDateTime);
    ftTime: Result := FormatDateTime('hhnnss', Field.AsDateTime);
    ftDateTime: begin
                  Result := FormatDateTime('yyyymmdd', Field.AsDateTime);
                  DecodeTime(Field.AsDateTime, Hour, Min, Sec, MSec);
                  if (Hour <> 0) or (Min <> 0) or (Sec <> 0) or (MSec <> 0) then
                    Result := Result + 'T' + GetDig(Hour, 2) + ':' + GetDig(Min, 2) + ':' + GetDig(Sec, 2) + GetDig(MSec, 3);
                end;
  else
    Result := Field.AsString;
  end;
end;

 

procedure DatasetToXML(Dataset: TDataset; FileName: string);
var
  Stream: TFileStream;
  bkmark: TBookmark;
  i: Integer;
begin
  Stream := TFileStream.Create(FileName, fmCreate);
  SourceBuffer := StrAlloc(1024);
  WriteFileBegin(Stream, Dataset);

  with DataSet do
  begin
    DisableControls;
    bkmark := GetBookmark;
    First;

    {write a title row}
    WriteRowStart(Stream, True);
    for i := 0 to FieldCount-1 do
      WriteData(Stream, nil, Fields[i].DisplayLabel);
    {write the end of row}
    WriteRowEnd(Stream, True);

    while (not EOF) do
    begin
      WriteRowStart(Stream, False);
      for i := 0 to FieldCount-1 do
        WriteData(Stream, Fields[i], GetFieldStr(Fields[i]));
      {write the end of row}
      WriteRowEnd(Stream, False);

      Next;
    end;

    GotoBookmark(bkmark);
    EnableControls;
  end;

  WriteFileEnd(Stream);
  Stream.Free;
  StrDispose(SourceBuffer);
end;

end.

 


  生成XML文件。
  我使用下面的轉(zhuǎn)換方法:
  I .   XML文件的根名與表名相同(本例就是country)。
  II.   每條來(lái)自于表的記錄由<record></record>標(biāo)記區(qū)分。
  III.  每個(gè)來(lái)自于表的數(shù)據(jù)由其字段名標(biāo)記加以區(qū)分。
  
  - <country> 
              - <Records> 
                        <Name>Argentina</Name> 
                        <Capital>Buenos Aires</Capital> 
                        <Continent>South America</Continent> 
                        <Area>2777815</Area> 
                        <Population>32300003</Population> 
                </Records> 
                        . 
                        . 
                        . 
     </country> 
  
  建立一個(gè)新的應(yīng)用程序。放置一個(gè)Button和Table構(gòu)件于主窗體上。設(shè)置表屬性如下:
                  DatabaseName : DBDEMOS 
                  Name : Table1 
                  TableName : country (Remove the extention ".db") 
                  Active : True 
  
  選擇 Project/Import Type library。將會(huì)彈出 "Import Type Library" 對(duì)話框。從列表中選擇 "Microsoft XML,Version 
  2.0(version 2.0)" 然后點(diǎn)擊 "Create Unit" 按鈕。將會(huì)有一個(gè) MSXML_TLB 單元加入你的工程.請(qǐng)將 MSXML_TLB 加入你要引用的單元的接口部分。然后在變量部分聲明如下變量:
                DataList : TStringlist; 
                  doc : IXMLDOMDocument; 
                  root,child,child1 : IXMLDomElement; 
                  text1,text2 : IXMLDOMText; 
                  nlist : IXMLDOMNodelist; 
                  dataRecord : String; 
  
  添加makeXml函數(shù)到你的單元。它將通過(guò)讀取DBDEMOS中contry表中的數(shù)據(jù)生成一個(gè)XML文件。
  function TForm1.makeXml(table:TTable):Integer; 
  var 
    i   : Integer; 
    xml,temp : String; 
  begin 
    try 
      table.close; 
      table.open; 
      xml  := table.TableName; 
      doc  := CreateOleObject('Microsoft.XMLDOM') as IXMLDomDocument; 
      //Set the root name of the xml file as that of the table name. 
      //In this case "country" 
      root := doc.createElement(xml); 
      doc.appendchild(root); 
      //This while loop will go through the entaire table to generate the xml file 
      while not table.eof do 
      begin 
        //adds the first level children , Records 
        child:= doc.createElement('Records'); 
        root.appendchild(child); 
        for i:=0 to table.FieldCount-1 do 
        begin 
          //adds second level children 
          child1:=doc.createElement(table.Fields[i].FieldName); 
          child.appendchild(child1); 
          //Check field types 
          case TFieldType(Ord(table.Fields[i].DataType)) of 
          ftString: 
          begin 
            if Table.Fields[i].AsString ='' then 
                 temp :='null'  //Put a default string 
               else 
                 temp := table.Fields[i].AsString; 
          end; 
  
          ftInteger, ftWord, ftSmallint: 
          begin 
              if Table.Fields[i].AsInteger > 0 then 
                 temp := IntToStr(table.Fields[i].AsInteger) 
               else 
                 temp := '0'; 
          end; 
          ftFloat, ftCurrency, ftBCD: 
          begin 
              if table.Fields[i].AsFloat > 0 then 
                temp := FloatToStr(table.Fields[i].AsFloat) 
              else 
                 temp := '0'; 
          end; 
          ftBoolean: 
          begin 
              if table.Fields[i].Value then 
                temp:= 'True' 
              else 
                temp:= 'False'; 
          end; 
          ftDate: 
          begin 
              if (not table.Fields[i].IsNull) or 
                 (Length(Trim(table.Fields[i].AsString)) > 0) then 
                temp := FormatDateTime('MM/DD/YYYY', 
                               table.Fields[i].AsDateTime) 
              else 
                temp:= '01/01/2000'; //put a valid default date 
          end; 
          ftDateTime: 
          begin 
              if (not table.Fields[i].IsNull) or 
                 (Length(Trim(table.Fields[i].AsString)) > 0) then 
                temp := FormatDateTime('MM/DD/YYYY hh:nn:ss', 
                               Table.Fields[i].AsDateTime) 
              else 
                temp := '01/01/2000 00:00:00'; //Put a valid default date and time 
          end; 
          ftTime: 
          begin 
              if (not table.Fields[i].IsNull) or 
                 (Length(Trim(table.Fields[i].AsString)) > 0) then 
                 temp := FormatDateTime('hh:nn:ss', 
                             table.Fields[i].AsDateTime) 
              else 
                 temp := '00:00:00'; //Put a valid default time 
          end; 
        end; 
         // 
         child1.appendChild(doc.createTextNode(temp)); 
        end; 
      table.Next; 
      end; 
      doc.save(xml+'.xml'); 
      memo1.lines.Append(doc.xml); 
      Result:=1; 
    except 
      on e:Exception do 
        Result:=-1; 
    end; 
  end; 
  
  在Button1的onclick事件中調(diào)用上面的函數(shù)
  procedure TForm1.Button1Click(Sender: TObject); 
  begin 
    if makeXml(table1)=1 then 
      showmessage('XML Generated') 
    else 
      showmessage('Error while generating XML File'); 
  end; 
  
  如果你用IE 5.0(或以上版本)打開(kāi)生成的country.xml文件,它看起來(lái)會(huì)成下面的樣子
  - <country> 
              - <Records> 
                        <Name>Argentina</Name> 
                        <Capital>Buenos Aires</Capital> 
                        <Continent>South America</Continent> 
                        <Area>2777815</Area> 
                        <Population>32300003</Population> 
                </Records> 
              - <Records> 
                        <Name>Bolivia</Name> 
                        <Capital>La Paz</Capital> 
                        <Continent>South America</Continent> 
                        <Area>1098575</Area> 
                        <Population>7300000</Population> 
                </Records> 
                        . 
                        . 
                        . 
              - <Records> 
                        <Name>Venezuela</Name> 
                        <Capital>Caracas</Capital> 
                        <Continent>South America</Continent> 
                        <Area>912047</Area> 
                        <Population>19700000</Population> 
                </Records> 
    </country> 
  
  插入數(shù)據(jù)
  
  你已經(jīng)將country表中存在的數(shù)據(jù)生成了XML文件。因此在這個(gè)XML文件中的數(shù)據(jù)就與country表中是一樣的。如果你想將XML文件中的數(shù)據(jù)插入進(jìn)country表中又不想刪除原來(lái)存在的數(shù)據(jù)的話,將會(huì)有主鍵沖突的錯(cuò)誤出現(xiàn)。因此必須先將country表中已經(jīng)存在的數(shù)據(jù)刪除掉。
  添加另一個(gè)按鈕和一個(gè)memo構(gòu)件于主窗體。在button2的onclick事件中添加如下代碼.memo用來(lái)顯示數(shù)據(jù)插入中的狀態(tài)(成功/失敗)。
  procedure TForm1.Button2Click(Sender: TObject); 
  var 
     i,ret_val,count:Integer; 
     strData:String; 
  begin 
      //Before inserting data in to the country table,make sure that the data in 
      //the generated xml file(country.xml) and country table(DBDEMOS) are 
      //different. 
      try 
        count:=1; 
        DataList:=TStringList.Create; 
        memo1.Clear; 
        doc := CreateOleObject('Microsoft.XMLDOM') as IXMLDomDocument; 
         //Load country.xml file 
        doc.load('country.xml'); 
        nlist:=doc.getElementsByTagName('Records'); 
        memo1.lines.append('Table Name  :country'); 
        memo1.lines.append('---------------------'); 
        for i:=0 to nlist.Get_length-1 do 
        begin 
           travelChildren(nlist.Get_item(i).Get_childNodes); 
           //Removes the first character(,) from dataRecord 
           strData:=copy(dataRecord,2,length(dataRecord)); 
           memo1.lines.append(strData); 
           dataRecord:=''; 
           ret_val:=insertintotable(Datalist); 
           if ret_val=1 then 
               memo1.lines.append('Data inserted successfully.............!') 
           else if ret_val=-1 then 
               memo1.lines.append('Error while updating.....Try again.....!'); 
           memo1.lines.append('=============================================' 
                              +'==(Record no. :'+inttostr(count)+')'); 
           DataList.Clear; 
           count:=count+1; 
        end; 
      except 
        on e:Exception do 
           Showmessage(e.message); 
     end; 
  end; 
  
  nlist(refer above program) contains a list of nodes.In our case the first node list is... 
  
          <Records> 
                        <Name>Argentina</Name> 
                        <Capital>Buenos Aires</Capital> 
                        <Continent>South America</Continent> 
                        <Area>2777815</Area> 
                        <Population>32300003</Population> 
                </Records> 
  
  
  我們傳送此節(jié)點(diǎn)列表給一個(gè)遞歸函數(shù),travelchildren。它將遞歸地沿著節(jié)點(diǎn)列表查找文本數(shù)據(jù),并將此數(shù)據(jù)加入TStringList(Datalist)變量中。當(dāng)完成第一輪后,Datalist中將會(huì)包含字符串 Argentina,Buenos Aires,South America,2777815,32300003.最后我們將此stringlist傳送給函數(shù) insertintotable,它將完成將一條記錄插入 country 表的工作。重復(fù)此過(guò)程即可完成整個(gè)XML文件數(shù)據(jù)的插入工作。
  procedure TForm1.travelChildren(nlist1:IXMLDOMNodeList); 
  var 
     j:Integer; 
     temp:String; 
  begin 
    for j:=0 to nlist1.Get_length-1 do 
    begin 
    //node type 1 means an entity and node type 5 means EntityRef 
    if((nlist1.Get_item(j).Get_nodeType= 1) or (nlist1.Get_item(j).Get_nodeType=5)) then 
      travelChildren(nlist1.Get_item(j).Get_childNodes) 
      //node Type 3 means a text node,ie you find the data 
      else if(nlist1.Get_item(j).Get_nodeType=3) then 
      begin 
        temp:= trim(nlist1.Get_item(j).Get_nodeValue); 
        dataRecord:=dataRecord+','+temp; //this is for displaying a single record on the memo 
        DataList.Add(temp); //Datalist will contain one record after completing one full travel through the node list 
      end 
    end; 
  end; 
  
  function TForm1.insertintotable(stpt:TStringList):Integer; 
  var 
    i:Integer; 
  begin 
    table1.close; 
    table1.open; 
    table1.Insert; 
    for i := 0 to stpt.Count - 1 do 
    begin 
         table1.Fields[i].AsVariant:= stpt[i]; 
    end; 
    try 
      table1.post; 
      result:=1; 
    except 
      on E:Exception do 
        result:=-1; 
    end; 
  end; 
  
  結(jié)論:
  你可以將此程序推廣至任何數(shù)據(jù)庫(kù),由此數(shù)據(jù)可以通過(guò)XML文件在網(wǎng)絡(luò)(即使是internet)中傳輸并在其實(shí)終端上更新數(shù)據(jù)庫(kù)。我在生成XML文件中還未考慮特殊字符如 &,<,>,',''等等。你可以在生成帶這些字符的XML文件時(shí)作適合自己需要的改變


上一篇:壓縮圖像文件并轉(zhuǎn)換成BMP格式

下一篇:術(shù)語(yǔ)VCL的變更:從VCL到CLX

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
學(xué)習(xí)交流
熱門圖片

新聞熱點(diǎn)

疑難解答

圖片精選

網(wǎng)友關(guān)注

主站蜘蛛池模板: 黄浦区| 冀州市| 武平县| 锦州市| 奉化市| 汨罗市| 承德市| 台前县| 永吉县| 太湖县| 远安县| 息烽县| 淳化县| 商都县| 昆明市| 玉门市| 肇庆市| 定西市| 奎屯市| 陇西县| 社旗县| 霸州市| 吴堡县| 新郑市| 乐亭县| 宁乡县| 绥滨县| 化德县| 商都县| 桃江县| 会理县| 七台河市| 建昌县| 洪雅县| 金门县| 龙胜| 丰原市| 南宁市| 福州市| 兴文县| 台中县|