Method for generating XML by database data (source code)

xiaoxiao2021-03-11  204

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 (S: String); Begin Strpcopy; Stream.write (SourceBuffer [0], Strlen; End;

Procedure Writefile Segin (Stream: TfileStream; DataSet: TDataSet);

Function XMLFieldType (FLD: TFIELD): String; begin case: result: = '"String" width = "' INTOSTOSTR (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 "; //? ? Ftdte: 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,' ');

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, '/>);

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

Function getfieldstr (Field: Tfield): String;

Function Getdig (I, J: Word): string; begin result: = INTOSTR (i); while (length)

Var Hour, min, sec, msec: word; begin case field.datatype of ftboolean: result: = Uppercase (FTDATE: RESULT: = formatdatetime ('YYYYMMDD', FIELD.ASDateTime); fttime: Result: = Formatdatetime ('hhnns', field.asdatetime); ftdatetime: begin result: = formatdatetime ('YYYYMMDD', FIELD.ASDatetime); Decodetime (Field.asdatetime, Hour, min, sec, msec); if (Hour <> 0) OR (MIN <> 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} Writerownd (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} Writerownd Stream, false;

NEXT; END;

Gotobookmark (BKMARK); ENABLECONTROLS;

Writefileend (stream); stream.free; strdispose; end;

End.

Generate an XML file. I use the following conversion method: i. The root name of the XML file is the same as the table name (this example is country). II. Each record from the table is distinguished by the tag. III. Each data from the table is distinguished by its field name. - - argentina BUENOS AIRES South America 2777815 32300003 . Create a new application. Place a Button and Table members on the main form. The set table properties are as follows: DatabaseName: DBDemos name: table1 tablename: Country (Remove the Extention ".db") Active: True Select Project / Import Type Library. The Import Type Library dialog will pop up. Select "Microsoft XML, Version 2.0 (Version 2.0)" from the list and click the "CREATE" button. There will be an MSXML_TLB unit to join your project. Please add MSXML_TLB to the interface part of the unit you want to reference. Then declare the variables in the variable section: DataList: TstringList; DOC: ixmldomdocument; root, child, child1: ixmldomelement; text1, text2: ixmldomtext; nlist: ixmldomnodelist; datarecord: string; add makexml functions to your unit. It will generate an XML file by reading data in the Contry table in DBDemos.

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 what of the table name. // in this case "country" root: = doc.createElement (xml); doc.appendchild (root); // this while 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] .dattype)) of ftstring: Begin If Table.fields [i] .sstring = '' THEN TEMP: = 'NULL' // Put A Default String Else Temp: = Table.fields [i] .sstring; end; ftinteger, ftword, ftsmallint: Begin if Table. Fields [i] .asinteger> 0 Tens: = INTOSTR (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 the temp: = 'true' else temp: = 'false'; end; ftdte: beginiff (not Table.fields [i] .isnull) or (Length) OR Trim (Table.fields [i] .sstring)> 0) THEN TEMP: = formatdatetime ('mm / dd / yyyy', table.fields [i] .asdatetime) else temp: = '01/01 / 2000 '; // put a valid default date end; ftdatetime: beginiff (not Table.fields [i] .isnull) or (table.fields [i] .sstring)> 0) THEN TEMP: = formatdatetime (' MM / DD / YYYY HH: NN: SS ', TABLE.FIELDS [I] .aDatetime) Else Temp: = '01 / 01/2000 00:00:00'; // Put a Valid Default Date and Time End; fttime : Begin IF (Not Table.fiel) DS [I] .NULL) OR (Length (Table.fields [i] .sstring)> 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 results: = - 1; end;

Call the above procedure TForm1.Button1Click function in onclick event of Button1 (Sender: TObject); begin if makeXml (table1) = 1 then showmessage ( 'XML Generated') else showmessage ( 'Error while generating XML File'); end; If you open the generated country.xml file with IE 5.0 (or above), it looks like it looks below - - argentina Buenos Aires South America 2777815 32300003 - Bolivia la PAZ South America 7300000 .. - Venezuela Caracas South America 912047 19700000 < / Country> Inserting data You have generated the data existing in the Country table generate an XML file. Therefore, the data in this XML file is the same as the Country table. If you want to insert the data in the XML file into the Country table and don't want to delete the original data, there will be an error in the primary key conflict. Therefore, you must first delete the data already existing in the Country table. Add another button and a MEMO component on the main form.

Add the following code in the Button2 onclick event. MEMO is used to display the status in the data insertion (success / fail).

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); Memo1.Lines.Append (strdata); DataRecord: = ''; RET_VAL: = Insertin Totable (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.: ' INTOSTR (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 copy the first node list is ... < Records> argentina Buenos Aires South America 2777815 32300003 We transfer This node lists gives a recursive function, TravelChildren. It looks a text data along the node list and add this data into the TStringList (DataList) variable. When the first round is completed, the DataList will include strings Argentina, Buenos Aires, South America, 2777815, 32300003. Finally, we will transfer this StringList to function insertintable, which will complete a record inserting a record into the Country table. Repeat this process to complete the insertion of the entire XML file data.

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 beg Table1.fields [i] .Asvariant: = stpt [i]; end; try table1.post; result: = 1; ExcePT ON E: Exception Do Result: = - 1; End; End; Conclusion: You can extend this program to any database, by This data can be transmitted in the network (even the Internet) through the XML file and update the database on the actual terminal. I have not considered special characters such as &, <,>, ',' ', and so on in generating XML files. You can make changes to you need when you generate XML files that come with these characters.

9CBS certified blog expert

Blog expert

Huawei old employees

Big Data

More than ten years, in Huawei, Internet Corporation's experience, profound understanding and practical experience in CRM, big data, mainly sharing various project experience, including architecture, Java, big data and other articles

转载请注明原文地址:https://www.9cbs.com/read-128960.html

New Post(0)