|
HTML clipboardI. Introduction XML, XML hence, the future is with us ... The least we can say is that XML is uproar in the world of IT and a fine figure on a CV. Many developments today revolve around the web, assistants pocket, WAP and others, it became necessary to define a universal standard description of data, regardless of the target platform. XML meets this requirement, at least in theory, because the phenomenon still has some way to go towards the standardisation, the various publishers interested did not usually s'amouracher on the question ... :-) II. XML? The goal is not to repeat a course on XML as long as you find anything learn about xml.developpez.com. But it is always useful to propose a few reminders succins. XML is nothing revolutionary. XML is a language that allows structuring data using a standard markup, like HTML. This allows applications to exchange data, "formatted" XML. Any developer can do the same this said, no need for XML, simply agree on a format between the client and server and interpret accordingly. The value of XML lies in the existence of libraries that implements the API standards of XML (DOM, SAX). And on many platforms. Even a proprietary technology like Flash (Macromedia) on board an XML parser. And so it becomes really interesting to design its data packets in XML format, where they are to be communicated to another service or system. For example, it was natural for any delphinautes use classes Inifiles.pas to manage and structure the *. ini. We will keep the concept but "version Starwars" ... with XML. Generally you extract data from an SQL, XML and the make-up on the forwards. But beware, XML is not intended and can not replace a SQL! Before continuing, it is preferable that you know the basics of XML, at least the basic vocabulary ( "root", "element", "attribute", "name" etc.). III. XML and Delphi 6
Delphi boxWe will see in this article how to create, read and go through an XML file the new components and experts newborn Delphi 6 (lovely baby). So for what purpose? The goal is to create a package of data organized in a flexible format and recognized by a maximum of platforms (which will then formatting of these data through a reading assisted through XML libraries of different languages). XML is very often used in an exchange mechanism: the data can be stored physically in a traditional DBMS, and converted to XML just for transmission. Examples: As mentioned above, one could compare an INI file to an XML file within the storage of information: An INI file contains sections and couples = value chain: [COMPANY] NAME = 4CENT AGENCY [CONTACT] NAME = Sylvain JAMES ADDRESS IS THE NETHERLANDS EMAIL sylvain.james = @ wanadoo.fr An XML file contains knots therefore presents a tree structure, the tree is presented by indentations lines: <Sylvain> <Societe>4CENT AGENCY</Societe> <Contact Name="JAMES Sylvain" Address="THE NETHERLANDS" email="
This e-mail address is being protected from spam bots, you need JavaScript enabled to view it
"/> </Sylvain> An XML file should (why not?) To store windows or even register an image of the file explorer. On the web, XML files are widely used as containers of information (Weather, News, TV programs, catalogues etc.) Which just draw on many other sites, which will then add a layer of presentation (in this context, see also side SOAP). One could also use the XML standard to represent the result of an SQL (what are already some DBMS as Oracle or SQLServer). Imagine two tables in relation master detail, participants in an internship for example.  A complaint as: SELECT Internships.NOMSTAGE, Internships.DATESTAGE, Trainees.NOMSTAGIAIRE, Trainees.AGESTAGIAIRE FROM internships, interns WHERE Internships.IDSTAGE = Trainees.IDSTAGE will return the data as follows:  The XML representation of the same data set will be as follows: <Internships> <Stage Name="WORD 2000 Initiation" Date="14/06/2001"> <Trainees> <Trainee Name="MAGIC Jordan" Age="35"/> <Trainee Name="ESSONCHA Jean-Roland" Age="38"/> </ Trainees> </ Stage> <Stage Name="SQL SERVER 7 Administration" Date="11/06/2001"> <Internships> <Trainee Name="DERIEN Pepito" Age="26"/> </ Trainees> </ Stage> <Stage Name="DELPHI 5 Perfectionnement" Date="01/06/2001"> <Trainees> <Trainee Name="SUSHI Okimi" Age="42"/> </ Trainees> </ Stage> </ Internships> It will not say that there is space saving with XML, but the presentation of data is radically different. In the case of SQL, the description of the fields is fixed but the data are repeated for each case (NOMSTAGE, DATESTAGE). In the XML representation, the data are not repeated, but are supervised by their description that seems more flexible. XML provides data on a tree describing each element and possibly its attributes. One element represents an entity, as <stagiaire> for example. An attribute is a property of an element, "Age" is an attribute of <stagiaire>. It must be said that the SQL is not appropriate when defining queries on data tree. XML can take over in these cases while keeping in mind that in terms of performance, XML révèrela significantly less than a DBMS (do not succumb to the comparison by the way, there is no need. ..). Delphi 6 offers tools for "map" data from Datasets (ClientDataSet, Query, Table ....) to XML. We see it in a forthcoming topo, here is how to build an XML document the mimine:  IV. A start at any Until then, it's not about encenser XML. But XML and its frangins also include tools that offer the opportunity to read and navigate an XML document, the interest is there. If you've already heard of DOM and SAX parsers, then you burn. These parsers are tools implementing API standard (and / or in progress ...) that provide interfaces to browse, search and edit information easily within an XML document. We support the API standard DOM (Document Object Model) through the implementation of Microsoft in msxml.dll (this lib must be registered as a COM server through Regsvr32.exe) if it is not yet (rare since installed with IE). That unity XMLDOM.pas which describes the interfaces implemented in bookstores DOM as specified by the W3C. For us the starting point will be located with the component XMLDocument: range of components, Tab Internet:  Ask a component XMLDocument on a blank form. List the XMLDoc (Name property). Without going into details, set the properties of this new kid as the next screenshot: The essential properties: * DOMVendor which lets you specify the library responsible for implementing DOM and if you want to work with existing XML document: * XML is a list of channels storing the XML document. To know that you are not obliged to allocate a list of chain ownership XML, you can also assign a name to file FileName property. * Active, which is when a component allows True XMLDocument to create and / or browse the tree nodes respective XML document. Any XML document starts with <? Xml version = "1.0" encoding = "UTF-8"?> Encoding may vary. Merely moving the Active property to true on a blank document XML, will add this line descriptive.
V. Creating XML structure The component includes a XMLDocument DocumentElement property type IXMLNode as each node of the tree. DocumentElement is unique, however, be the root (the root) of the tree. If one takes the example of XML document on Training / Fellows, is the root node <stages>. The document must include a mandatory root. We will create a node (IXMLNode) and affect the property DocumentElement. This node will be the starting point, the reference from which we will create other nodes, the nodes children. HTML clipboard HTML clipboardTechnical reminder IXMLNode is a class interface and not a class of object. As such, its function is to present a list of methods, but without their implementation. This charge is for classes managing interfaces (mostly heriees of TInterfacedObject). The same class can implement multiple interfaces. The XML classes are no exception. For example, the class TXMLNode implements - among others - the interface IXMLNode. : TXMLNode = class (TInterfacedObject, IXMLNode, IXMLNodeAccess) A variable may be declared type interface (as IXMLNode), but must be instantiated with a class object implementing this interface (such as class TXMLNode). Place a button and a memo on the form, name the btnCreation and implement its manager OnClick in the following manner: TForm1.btnCreationClick procedure (Sender: TObject); var internship, interns, trainee: IXMLNode / / Knots reference Begin memo1.Clear; / / Creation of the first node 'internship' and initialization DocumentElement XMLDoc.DocumentElement: = XMLDoc.CreateElement ( 'courses',''); / / Creation of the first child node, representing the first stage Internship: XMLDoc.DocumentElement.AddChild = ( 'stage'); / / Creation Attribute this stage stage.Attributes [ 'name'] = 'WORD 2000 Initiation'; stage.Attributes [ 'date']: ='14 / 06/2001 '; / / Creation of child node of this course: Trainees Interns: = stage.AddChild ( 'trainees'); / / Create each trainee Intern: =Trainees.AddChild ( 'trainee'); Trainees.Attributes [ 'name'] = 'MAGIC Jordan'; Trainees.Attributes [ 'age']: ='35 '; / / 2nd trainee Intern: = Trainees.AddChild ( 'trainee'); Trainees.Attributes [ 'name'] = 'ESSONCHA Jean-Roland'; Trainees.Attributes [ 'age']: ='38 '; / / Next Stage Internship: XMLDoc.DocumentElement.AddChild = ( 'stage'); / / Creation Attribute this stage stage.Attributes [ 'name'] = 'SQL SERVER 7 Hotel'; stage.Attributes [ 'date']: ='11 / 06/2001 '; / / and so on //... the end you can see the result! Simplissimo :-) memo1.Lines.Assign (XMLDoc.XML); end; At this stage, with 2 methods and a property, we have created an XML document representing a prioritized list of courses and their respective trainees. It is easy to complete the above code with an interface offering fields of publishing and buttons to add an internship or a trainee. * The CreateElement returns the node type IXMLNode that is created. * The AddChild also returns IXMLNode node that is created, but it is created from another node and not the document. The crux created node becomes child who called this function. * The property Attributes can be mapped a keyword and assign a value. Attributes here applies to a designated node. To conclude this first part, save the XML document in the folder of your choice by calling the method of SaveToFile XMLDocument object: XMLDoc.SaveToFile ( 'stages.xml'); For a first look, you can read this XML document with your Web browser, you will see that he knows "present" the document with a tree line with your description. HTML clipboardVI. The expert Data Link Let us continue our exploration XML and Delphi 6 and now see the expert [Data Link XML] and navigation in an XML structure: We want to read an XML file exists. Delphi 6 proposes seizing an expert who analyzes the structure of an XML document and creates types interface that "map" elements and attributes of the document. Then, just include the reporting of these types in your units Delphi, the magic happens For example, click on the icon and select the New icon XML Data Binding: The expert will then ask you what XML file must be analysed; change the type of files so that *. xml be filtered and then specify the path and file name XML (we'll take an example provided with Delphi: Delphi6 \ Demos \ WebSnap \ XSLProducer \ recipes.xml) and click Next. We get the next screen.
HTML clipboard Therefore, a unit is processed. All types needed to read the XML file underlying are declared and implement interfaces IXMLNode and IXMLNodeCollection as nodes contain elements that are repeated (trainees) or not (student). Three methods utilities are also declared and implemented: GetRecipe function (Doc: IXMLDocument): IXMLRecipeType; LoadRecipe function (const FileName: WideString): IXMLRecipeType; NewRecipe function: IXMLRecipeType; GetRecipe allows component of the linker XMLDocument analyzed the structure, wholesale initialize document root in instanciant a variable IXMLRecipeType. LoadRecipe can load an existing file. NewRecipe offers the possibility to start from scratch. In 3 cases, we get in return for a variable depending on type IXMLRecipeType who will be our starting point to navigate through the tree. Here is an excerpt of the interface is: ... IXMLRecipeType () IXMLRecipeType = interface (IXMLNode) [ '(F93E8345-8F0D-472A-B9A3-17F365247A42)'] Accessors properties () Get_Name function: WideString; Get_Description function: WideString; Get_Ingredients function: IXMLIngredientsType; Get_Instructions function: IXMLInstructionsType; procedure Set_Name (Value: WideString); Set_Description procedure (Value: WideString); Methods & properties () property Name: WideString read Get_Name write Set_Name; property Description: WideString read Get_Description write Set_Description; property Ingredients: IXMLIngredientsType read Get_Ingredients; property Instructions: IXMLInstructionsType read Get_Instructions; end; IXMLIngredientsType () IXMLIngredientsType = interface (IXMLNodeCollection) [ '(BAB79B24-ED85-4141-B3C9-A36729D1FEA8)'] Accessors properties () Get_Ingredient function (Index: Integer): IXMLIngredientType; Methods & properties () Add function: IXMLIngredientType; Insert function (const Index: Integer): IXMLIngredientType; Ingredient property [Index: Integer]: IXMLIngredientType read Get_Ingredient; default; end; ... Enregistrons this unit and then add in the uses of our application of departure and declare a variable IXMLRecipeType: var recipe: IXMLRecipeType; Begin / / Initialisons this variable thanks to the GetRecipe processed by the expert recipe: = GetRecipe (XMLDoc); Now, the variable recipe is our starting point. It was interfaced with the assistant in order to help us as much as possible its use. After loading the file 'recipe.xml' in the component XMLDoc via FileName property ... : Try this in a manager OnClick any of a button (also a plan for TMemo logger messages). var recipe: IXMLRecipeType; i: integer; Begin recipe: = GetRecipe (XMLDoc); for i: = 0 to recette.Ingredients.Count - 1 do memo2.Lines.Add (recette.Ingredients [i]. Item); end; or: memo2.Lines.Add (recette.Name); //... memo2.Lines.Add (recette.Ingredients [i]. Qty [0]. Attributes [ 'unit']); This last example shows that in the expert, you would have remove the check mark [Repeat] to attribute Qty (see diagram below) because it is an attribute and not only a list of same attribute in the document recipe.xml. To you to specify in the wizard because the latter can hardly guess. Just to make a double-click on the component XMLDocument to reveal the expert Data Link XML and this time, we select the node and décochons Qty box Repeat:  HTML clipboard HTML clipboard You generate a new unity, and in relation to the unit created, this time you can encode in the following manner: * Memo2.Lines.Add (recette.Ingredients [i]. Qty.Attributes [ 'unit']) / / instead ... * Memo2.Lines.Add (recette.Ingredients [i]. Qty [0]. Attributes [ 'unit']); Qty implement because IXMLNode and non IXMLNodeCollection. VI. Conclusion In short, you is a fantastic tool to generate your XML templates and frankly it would be a shame to miss. We only skimmed over what Delphi 6 brought us in terms of development XML, there are still interesting discoveries as XML Mapper tool processing data from a Dataset to XML and vice versa and many other things yet. I will come back soon, and accumulating know-how, we will be able to use XML wisely. Think of your resume .... :-))) Sylvain James Developer / Trainer
|