How to create xml file delphi. Internet travel guide - all the fun on the web. A few words about the organization of document flow
Welcome! This blog is about the Internet and computers, or rather it was dedicated to them.
Probably, it is immediately clear that no new articles have appeared on the site for many years. Yes, that's the fate of most blogs. This project was once an ambitious undertaking, and the author, like many others who wrote at the time, had ambitious plans to become one of the best Russian bloggers. Well, if you look now, then of those blogs that were created simultaneously with mine, most have already disappeared into eternity. And I just didn't have enough time to blog. So yes, it is not being updated anymore. Although once we with this site won the competition "Blog of Runet 2011".
I even had the idea to delete all this, but then I revised the old materials, and realized that they can still be useful to readers. Yes, some articles are outdated (if I have enough strength, they will receive appropriate notes), but the site, for example, can be useful for beginners - here you can read about basic concepts Internet, learn how to configure the Internet, Windows, or even decide to switch to Linux. So look at the rubrics and choose the one that's right for you.
And yet, I hope this is more than just a blog, but a real guide to the Internet. The site can be viewed in the directory mode, where all available articles are structured by category. And who knows, maybe one day new high-quality articles will start appearing here.
Sander
Picodi.ru is a discount portal from International Coupons, a Polish expert in savings and cheap shopping. Poles are considered one of the most economical nations in the world, so it is not surprising that this type of project grew out of the Polish startup kodyrabatowe.pl. How can this portal be useful to an ordinary Internet user in Russia?
Modern android phones are more than phones. You get used to typing installed programs, to the history of your calls and text messages, photo collections and more. But time passes, and the device that suits you completely begins to slow down, glitch, or simply loses its presentable appearance due to chips on the case or scratches on the screen. The question arises of choosing a new phone and changing android phone... And if we now bypass the question of choice, then "moving" to new phone remains a serious problem - you absolutely do not want to start all the data from scratch. This is what we are going to talk about today.
Most of the readers of this blog, most likely, have never encountered version control systems and will not come across any in the near future. It's a pity. This extremely convenient invention is widely used by programmers, but, in my opinion, it could be very useful for those who actively work with texts. But, probably, now there is not a single version control system that would be easy to start using for "office" ( Microsoft Office) work. Nevertheless, I think that the material presented in the article may be interesting for all readers.
If you have thought about how to watch movies on the network from your TV and go online, this article is for you. No, I know that some TVs already have Smart TV functionality, but I have never seen it work properly. Apparently, therefore, recently the Google corporation demonstrated an absolutely stunning device, which immediately became a sensation. We're talking about the Chromecast media streamer (Chromecast), a more advanced and affordable version of last year's disastrous Nexus Q.
Dongle Chromecast, which is no more than 2 inches in size, plugs into the port HDMI TV and allows you to enjoy watching streaming web content. To control the streamer, you can use any device (tablet, PC, smartphone) based on the operating platform iOS, Windows, Android or Mac OS.
This article is devoted to the device of the android system memory, the problems that may arise due to its lack and how to solve them. Not so long ago, I myself was faced with the fact that my android phone began to regularly give out messages about insufficient memory when trying to install an application. Which was very strange for me, given that according to the description on the market there should have been about 16GB, and I also increased this volume with an additional memory card. However, there was a problem, and I had to tinker a lot before I found correct solution that does not require root access or a full factory restore of the phone.
XML is increasingly being used to store information and exchange it between applications and Web sites. Many applications use this language as the base language for storing data, while others use it for exporting and importing XML data. So it’s time for developers to start thinking about how XML data can be used in their own applications.
In this article, we'll look at the XML Document Object Model (DOM) and Microsoft's implementation of the XML DOM.
The XML DOM is an object model that provides a developer with objects for loading and processing XML files. The object model consists of the following core objects: XMLDOMDocument, XMLDOMNodeList, XMLDOMNode, XMLDOMNamedNodeMap, and XMLDOMParseError. Each of these objects (except XMLDOMParseError) contains properties and methods that allow you to get information about the object, manipulate the object's values and structure, and navigate the structure of an XML document.
Let's look at the main XML DOM objects and show some examples of their use in Borland Delphi.
Using XML DOM in Borland Delphi
In order to use Microsoft XML DOM in Delphi applications, you need to connect the appropriate type library to the project. To do this, we execute the command Project | Import Type Library and in the Import Type Library dialog box, select the Microsoft XML version 2.0 (Version 2.0) library, which is usually located in the Windows \ System \ MSXML.DLL file
After clicking the Create Unit button, the MSXML_TLB interface module will be created, which will allow us to use the XML DOM objects: DOMDocument, XMLDocument, XMLHTTPRequest and a number of others, implemented in the MSXML.DLL library. The reference to the MSXML_TLB module must be in the Uses list.
XML DOM device
The Document Object Model represents an XML document in a tree structure of branches. XML DOM APIs allow applications to navigate the document tree and manipulate its branches. Each branch can have a specific type (DOMNodeType), according to which the parent and child branches are determined. Most XML documents contain branches of type element, attribute, and text. Attributes are a special kind of branch and are not child branches. Special methods provided by XML DOM objects are used to manipulate attributes.
In addition to implementing World Wide Web Consortium (W3C) recommended interfaces, the Microsoft XML DOM contains methods that support XSL, XSL Patterns, Namespaces, and data types. For example, the SelectNodes method allows you to use XSL Pattern Syntax to find branches in a specific context, and the TransformNode method supports using XSL to perform transformations.
Test XML Document
As an example XML document, let's take a music CD-ROM directory, which has the following structure:
We are now ready to start looking at the XML DOM object model, starting with the XMLDOMDocument object.
XML Document - XMLDOMDocument Object
Working with an XML document begins with loading it. To do this, we use the Load method, which has only one parameter that specifies the URL of the loaded document. When loading files from a local disk, only the full file name is specified (the file: /// protocol can be omitted in this case). If the XML document is stored as a string, use the LoadXML method to load the document.
The Async property is used to control how the document is loaded (synchronous or asynchronous). By default, this property is set to True, indicating that the document is loaded asynchronously and control is returned to the application before the document is fully loaded. Otherwise, the document loads synchronously, and then you have to check the value of the ReadyState property to find out if the document has loaded or not. You can also create a handler for the OnReadyStateChange event that will take control when the value of the ReadyState property changes.
The following shows how to load an XML document using the Load method:
Uses ... MSXML_TLB ... procedure TForm1.Button1Click (Sender: TObject); var XMLDoc: IXMLDOMDocument; begin XMLDoc: = CoDOMDocument.Create; XMLDoc.Async: = False; XMLDoc.Load (‘C: \ DATA \ DATA.xml’); // // This is where the code that manipulates // the XML document and its branches // XMLDoc: = Nil; end;
After the document is loaded, we can access its properties. So, the NodeName property will contain the #document value, the NodeTypeString property will contain the document value, and the URL property will contain the file: /// C: /DATA/DATA.xml value.
Error handling
Of particular interest are properties related to document processing upon loading. For example, the ParseError property returns an XMLDOMParseError object containing information about an error that occurred while processing the document.
To write an error handler, you can add the following code:
Var XMLError: IXMLDOMParseError; ... XMLDoc.Load (‘C: \ DATA \ DATA.xml’); XMLError: = XMLDoc.ParseError; If XMLError.ErrorCode<>0 Then // // Here we handle the error // Else Memo1.Lines.Add (XMLDoc.XML); ... XMLDoc: = Nil;
To find out what information is returned in case of an error, change the following directory entry:
removing the closing element
Now let's write code that returns the property values of the XMLDOMParseError object:
XMLError: = XMLDoc.ParseError; If XMLError.ErrorCode<>0 Then With XMLError, Memo1.Lines do begin Add (‘File:’ + URL); Add (‘Code:’ + IntToStr (ErrorCode)); Add (‘Error:’ + Reason); Add (‘Text:’ + SrcText); Add (‘Line:’ + IntToStr (Line)); Add (‘Position:’ + IntToStr (LinePos)); end Else Memo1.Lines.Add (XMLDoc.XML); End;
and execute our application. As a result, we get the following information about the error.
As you can see from the above example, the information returned by the XMLDOMParseError object is quite enough to localize the error and understand the cause of its occurrence.
Now we will restore the closing element
Accessing the document tree
To access the document tree, you can either get the root element and then iterate over its child branches, or find a specific branch. In the first case, we get the root element through the DocumentElement property, which returns an object of type XMLDOMNode. Here's how to use the DocumentElement property to get the contents of each child element:
Var Node: IXMLDOMNode; Root: IXMLDOMElement; I: Integer; ... Root: = XMLDoc.DocumentElement; For I: = 0 to Root.ChildNodes.Length-1 do Begin Node: = Root.ChildNodes.Item [I]; Memo1.Lines.Add (Node.Text); End;
For our XML document, we get the following text.
If we are interested in a specific branch or a branch below the first child branch, we can use either the NodeFromID method or the GetElementByTagName method of the XMLDOMDocument object.
The NodeFromID method requires a unique identifier as defined in the XML Schema or Document Type Definition (DTD) and returns a branch with that identifier.
The GetElementByTagName method requires a string with a specific element (tag) and returns all branches with this element. Here's how to use this method to find all the artists in our CD-ROM directory:
Nodes: IXMLDOMNodeList; Node: IXMLDOMNode; ... Nodes: = XMLDoc.GetElementsByTagName (‘ARTIST’); For I: = 0 to Nodes.Length-1 do Begin Node: = Nodes.Item [I]; Memo1.Lines.Add (Node.Text); End;
For our XML document, we will get the following text
Note that the SelectNodes method of the XMLDOMNode object provides a more flexible way to access document branches. But more on that below.
Document Branch - XMLDOMNode Object
The XMLDOMNode object represents a document branch. We already encountered this object when we got the root element of the document:
Root: = XMLDoc.DocumentElement;
To obtain information about a branch of an XML document, you can use the properties of the XMLDOMNode object (Table 1).
To access the data stored in a branch, it is common to use either the NodeValue property (available for attributes, text branches, comments, processing instructions, and CDATA sections), or the Text property, which returns the textual content of the branch, or the NodeTypedValue property. The latter, however, can only be used for branches with typed items.
Navigating the document tree
The XMLDOMNode object provides many ways to navigate the document tree. For example, to access the parent branch, use the ParentNode property (type XMLDOMNode), access the child branches through the ChildNodes properties (type XMLDOMNodeList), FirstChild and LastChild (type XMLDOMNode), etc. The OwnerDocument property returns an XMLDOMDocument object that identifies the XML document itself. The properties listed above make it easy to navigate the document tree.
Now let's loop through all the branches of the XML document:
Root: = XMLDoc.DocumentElement; For I: = 0 to Root.ChildNodes.Length-1 do Begin Node: = Root.ChildNodes.Item [I]; If Node.HasChildNodes Then GetChilds (Node, 0); End;
As noted above, the SelectNodes of the XMLDOMNode object provides a more flexible way to access document branches. In addition, there is a SelectSingleNode method that returns only the first branch of the document. Both of these methods allow you to define XSL templates for branch searches.
Let's look at the process of using the SelectNodes method to fetch all branches that have a CD branch and a PRICE sub-branch:
Root: = XMLDoc.DocumentElement; Nodes: = Root.SelectNodes (‘CD / PRICE’);
All PRICE sub-branches of the CD branch will be placed in the Nodes collection. We'll come back to discussing XSL templates a bit later.
Manipulating child branches
To manipulate child branches, we can use the methods of the XMLDOMNode object (Table 2).
In order to completely delete the record about the first disk, you need to run the following code:
Var XMLDoc: IXMLDOMDocument; Root: IXMLDOMNode; Node: IXMLDOMNode; XMLDoc: = CoDOMDocument.Create; XMLDoc.Async: = False; XMLDoc.Load (‘C: \ DATA \ DATA.xml’); // Get the root element Root: = XMLDoc.DocumentElement; Node: = Root; // Remove the first child branch Node.RemoveChild (Node.FirstChild);
Note that in this example we are deleting the first child branch. How to remove the first element of the first child branch is shown below:
Var XMLDoc: IXMLDOMDocument; Root: IXMLDOMNode; Node: IXMLDOMNode; XMLDoc: = CoDOMDocument.Create; XMLDoc.Async: = False; XMLDoc.Load (‘C: \ DATA \ DATA.xml’); // Get the root element Root: = XMLDoc.DocumentElement; // and the first child branch Node: = Root.FirstChild; // Remove the first child branch Node.RemoveChild (Node.FirstChild);
In the above example, we deleted not the first branch
Now let's add a new branch. Below is the code showing how to add a new music CD-ROM entry:
Var NewNode: IXMLDOMNode; Child: IXMLDOMNode; ... // Create a new branch -
The above code shows the following sequence of steps to add a new branch:
- Creating a new branch using the CreateNode method:
- creating an element using the CreateNode method;
- adding an element to a branch using the AppendChild method;
- setting the value of an element through the Text property;
- … Repeat for all elements.
- Adding a new branch to the document using the AppendChild method.
Recall that the AppendChild method adds a branch to the end of the tree. In order to add a branch to a specific place in the tree, you need to use the InsertBefore method.
Branch set - XMLDOMNodeList object
The XMLNodeList object contains a list of branches, which can be built using the SelectNodes or GetElementsByTagName methods, and also obtained from the ChildNodes property.
We have already discussed the use of this object in the example provided in the section "Navigating the document tree". Here we will provide some theoretical comments.
The number of branches in the list can be obtained as the value of the Length property. The branches are indexed from 0 to Length-1, and each individual branch is accessible through the corresponding indexed item in the Item array.
Navigating through the list of branches can also be done using the NextNode method, which returns the next branch in the list, or Nil if the current branch is the last. To return to the top of the list, call the Reset method.
Create and save documents
So, we've covered how you can add branches and elements to existing XML documents. Now let's create an XML document on the fly. First of all, remember that a document can be loaded not only from a URL, but also from a regular string. Here's how to create a root element, which can then be used to dynamically build the rest of the elements (which we already covered in the Manipulating Child Branches section):
Var XMLDoc: IXMLDOMDocument; Root: IXMLDOMNode; Node: IXMLDOMNode; S: WideString; ... S: = ‘
After building the XML document, save it to a file using the Save method. For example:
XMLDoc.Save ('C: \ DATA \ NEWCD.XML');
In addition to saving to a file, the Save method allows you to save an XML document in a new XMLDOMDocument object. In this case, the document is fully processed and, as a result, its structure and syntax are checked. Here's how to save a document to another object:
Procedure TForm1.Button2Click (Sender: TObject); var XMLDoc2: IXMLDOMDocument; begin XMLDoc2: = CoDOMDocument.Create; XMLDoc.Save (XMLDoc2); Memo2.Lines.Add (XMLDoc2.XML); ... XMLDoc2: = Nil; end;
In conclusion, the Save method also allows you to save the XML document to other COM objects that support the IStream, IPersistStream, or IPersistStreamInit interfaces.
Using XSL Templates
When discussing the SelectNodes method of the XMLDOMNode object, we mentioned that it provides a more flexible way to access document branches. The flexibility is that you can specify an XSL template as the criteria for selecting branches. Such templates provide a powerful mechanism for finding information in XML documents. For example, to get a list of all the music CD-ROM titles in our directory, you can run the following query:
To find out which artists' discs are released in the USA, the request is formed as follows:
Nodes: = Root.SelectNodes (‘CD / ARTIST’);
Here's how to find the first drive in a directory:
Nodes: = Root.SelectNodes (‘CD / TITLE’);
And last:
Nodes: = Root.SelectNodes (‘CD / TITLE’);
To find Bob Dylan's disks, you can run the following query:
Nodes: = Root.SelectNodes (‘CD [$ any $ ARTIST =” Bob Dylan ”] / TITLE’);
and to get a list of disks made after 1985, we run the following query:
Nodes: = Root.SelectNodes (‘CD / TITLE’);
A more detailed discussion of XSL syntax requires a separate publication. To intrigue readers and encourage further research, I will give just one small example of the possible use of XSL. Let's say we need to convert our catalog to a regular HTML table. Using the traditional methods, we must iterate over all the branches of the tree and for each received element form the corresponding tags
Using XSL, we simply create a template (or stylesheet) that specifies what to transform and how. Then we overlay this template on our catalog - and you're done: we have the text of an XSL template that transforms the catalog into a table (Listing 2).
The code to overlay an XSL template on our directory looks like this:
Procedure TForm1.Button2Click (Sender: TObject); var XSLDoc: IXMLDOMDocument; begin XSLDoc: = CoDOMDocument.Create; XSLDoc.Load (‘C: \ DATA \ DATA.xsl’); Memo2.Text: = XMLDoc.TransformNode (XSLDoc); XSLDoc: = Nil; end;
Concluding our discussion of XSL, it should be said that at present this language is actively used for transformation between various XML documents, as well as for formatting documents.
Conclusion
For obvious reasons, it is impossible to cover all Microsoft XML DOM objects and provide examples of their use in one article. Here we have just touched on the basic issues of using XML DOM in applications. Table 3 shows all the objects implemented in the Microsoft XML DOM.
ComputerPress 12 "2000
For many Delphi programmers, saving settings is associated with using INI files in their programs. The use of this method, in more or less serious projects, should be avoided, as it limits flexibility, which prevents further expansion of the program. It should be said that this approach is quite popular due to its ease of use and the presence of built-in tools in the development environment.
However, structured XML files. Their advantage is that the number of parameters may not be fixed. To understand this better, consider a specific example.
In the USearch program, when you click on an entry, a context menu appears, in which a list of items is displayed. These items are commands, which in turn are loaded from the settings file. In case the settings were stored in INI file, then the program could save and load a certain number of commands, for example 10 or 50. As soon as a larger value is required, you will have to rewrite the code and re-compile it accordingly.
Applying an approach using XML files, we will be able to load all section parameters dynamically. In addition, the configuration file will become more elegant, without redundant parameter numbering. However, the standard tools for working with XML Delphi has many disadvantages, so I recommend using the standard library MSXML... Usually it is included by default with the operating systems of the Windows family.
To connect MSXML, we need to generate an interface file with a list of all functions by importing it from the COM server. Many detailed articles have been written on how to import the interface, but I suggest you download the file MSXML2_TLB.PAS ready to use. After the file is downloaded, place it next to your project, or drop it into the lib folder of the Delphi environment. Thus, all created programs will be able to use the module MSXML, you just need to add the MSXML2_TLB line to uses.
For clarity, consider the following example of using this library:
Procedure LoadData; var XMLDoc: DOMDocument; Root: IXMLDOMElement; begin XMLDoc: = CoDOMDocument.Create; XMLDoc.Load ("settins.xml"); Root: = XMLDoc.DocumentElement; ShowMessage (Root.SelectSingleNode ("size / width"). Text); Root: = nil; XMLDoc: = nil; end;
First, an instance of the DOMDocument class is created, and then the contents of the settings.xml file are loaded into memory. Since, according to the standard, any XML the file must contain the root tag (in this case config), then we need to get it using the function DocumentElement... Then the content is displayed between the tags.
Here the SelectSingleNode method is applied, which takes a string as a parameter
ORDER PROBLEM SOLUTION ON DELPHI
Delphi is the second most important programming language that students are most often introduced to in the learning process. This is the beginning of learning about object-oriented programming. As a student, I came to the conclusion that there is no easier method to learn a language than to write a calculator in it. Even if you implement a rudimentary function for adding two numbers, it will shed a lot of light on it.
CodeGaear, Delphi 7, Lazarus are different compilers, programs that will transfer the code you write to the machine, converting it to ones and ones. These are all programs for creating programs, not separate programming languages. These compilers use the Object Pascal programming language, which is the basis of the Delphi language, which is similar in syntax to regular Pascal, but functionally differs significantly.
What is the syntax of a programming language?
This is the format for writing various operators. For example, a Pascal "for" loop has the following format: "for n: = 1 to k do" and so on.
In the C ++ programming language, the same loop is written a little differently: for (n = 1; n We write a calculator
This will give you an understanding of how objects interact with program code, what "variables" are, and how mathematical functions work. Any programming will be a computation anyway. A game is also a program that constantly calculates something, works with numbers and numerical functions. Programming is inseparable from mathematics.
Let's use the Lazarus development environment for writing. Its functionality is not as rich as, say, CodeGear, but it is freely available and is intended for training.
Opening the development environment, we see the form and the toolbox. Here is the form.
Here is the toolbox.
The first thing we will do is add the three elements we need to implement the function for adding two numbers. We need: "Tedit" in the amount of three pieces and "TButton". In the picture below they are shown on the panel with arrows. We click on them once, and then once on the form, and they appear on it.
These are text fields for input and a regular button. You come across these elements using almost any Windows program. Take a look.
Now let's clean up these labels. Click the "View" tab. And click on the item "Object Inspector. A window like this will appear.
We click once on our "Button" element on the form and change the "Caption" value in the inspector window to any other. For example, the word "Ok". We press Enter. We see on the form how the element has changed its name.
We will do the same with Edit's, only we will not rename, but we will make them without any content. Select them in turn and clear the Text value in the inspector. Do not forget to press Enter.
As a result, our form looks like this.
Now, for our calculator to work, you need to write the necessary program code for the procedure of our button. Click on the Button element twice and open the source editor.
See? Procedure Button1Click. This is the procedure that is responsible for what happens when we click on the button once. And the following should happen: the program needs to display the sum of the numbers entered in the first two fields in the third Edit. We write the code.
We need to write such simple 5 lines of code. Comments and explanations can be seen in the picture above. After that, we press this button.
Our project will be compiled. It will be compiled into a program. We enter numbers in the first two fields, click on the button and get the value of the sum.
Conclusion
You can click the "File" button, then "Save All", select a folder to save and you will have a full-fledged program that can be launched from the desktop. Now try to figure out for yourself what you need to rewrite in this code so that the program divides two numbers, and does not add. Hint: you need to change the data type. The video below shows a similar example, but in the Delphi 7 environment, not Lazarus.
Recently, much attention has been paid to building e-business systems, or as they are also called - B2B (business to business). Considering the recommendations on the construction of exchange streaming systems of the coordinating body of Internet technologies - WWW Consortium: the emphasis is on XML technologies and the construction of systems for the exchange of XML documents.
The advantage of using XML in e-business is the high efficiency of B2B systems at low costs for its creation due to a clear and visual presentation of structured information, the ability to use modern network protocols and create real-time business systems.
The independence of the presentation of information in the form of XML documents allows different companies involved in e-business to produce software independently of each other.
In all systems, the exchange, as a rule, is built according to the same scheme, using HTTP requests. SSL is used as the information security protocol (but this is a separate topic).
One of the possible options for processing XML messages is to build BIN / CGI (ISAPI) applications or COM (server) components that generate or process XML documents.
On the one hand, the application acts as a client, which issues an HTTP request in POST mode, on the other hand, there is a WEB server on the side of which the request is processed and a response is issued. The information exchange uses XML documents.
One of the most efficient implementation options is to use an existing XML parser that supports the DOM model. Such a parser is a distribution package of Win'98 or an integral part of IE 4.7 and higher (for Win'95) and represents a COM server located in the msxml.dll library.
Component Object Model (COM) - Represents encapsulated data and methods into a single entity and a way to access them through a system of interfaces. Using Delphi tools, it is quite easy to access the classes of a COM object (several classes can be included in one COM server). Objects are accessed by initializing an instance of the class through the interface system. The description of interfaces is carried out by the interface definition language (IDL), which can be carried out by means of the environment automatically.
Delphi tools are used to import from a COM server msxml.dll, the files for the description of the IDL interface and the file for the binary description of the library types - TLB are built. This operation is carried out through the system menu: Project | Type Library Import:(picture 1). Next, a dialog box appears (Figure 2), in which you need to select a COM object (in our case, the object is registered under the name "Microsoft.XMLDom (Version 2.0)") and create a TLB file (button Create unit). Using the TLB file, the framework generates a "Pascal" COM server description file - MSXML_TLB.pas
The MSXML_TLB.pas file describes all the interfaces, constants, and coclasses of the COM server.
To access objects of a COM element, you need in the directive USES add the name of the library description file (MSXML_TLB.pas). Below is a simple program using the standard DOM parser msxml.dll, which loads an XML document and displays it in a Memo1 text field element.
uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OleServer, MSXML_TLB, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click (Sender: TObject); end; var Form1: TForm1; implementation($ R * .DFM) Procedure TForm1.Button1Click (Sender: Tobject); // declaration of the soclass of the DOMDocument object; var coDoc: CoDOMDocument; // class consistent with the IDOMDocument interface; var Doc: IXMLDOMDocument; begin // create an instance of the DOMDocument object; Doc: = coDoc.Create; // call the Load method of an instance of the DOMDocument object; Doc.load ("data.xml"); // access the xml property of the DOMDocument instance; Memo1.Text: = Doc.xml; end; end.DOM Concept - Document Object Model
Each XML document is represented as a set of multiple objects (classes), with the help of which it is possible to access individual elements (object fields). DOM - the interface describes access both to simple objects of the DOMString or CharacterData type, and to parts or individual elements of an XML document: DOMFragmentElement, DOMNode, DOMElement.
Following are the most important properties and methods of XMLDOMDocument, XMLDOMNode, XMLDOMNodeList objects. It should be noted that the methods and functions of the Document Object Model (DOM) objects presented below are used by the Microsoft XML parser msxml.dll and are somewhat broader than the DOM model approved by the W3C Consortium.
A more complete description of the DOM object interface can be found at
XMLDOMDocument object | |
Represents the top level of the object hierarchy and contains methods for working with a document: loading it, analyzing it, creating elements, attributes, comments, etc. ... | |
Properties | |
Async | Property identifying the current processing mode |
ParseError | Returns a reference to the XMLDOMParseError error handling object |
Enable - disable document verification. | |
url | Returns the URL of the document |
documentElement | Contains a reference to the root element of the document as an XMLDOMElement object. |
Methods | |
load (url) loadXML (xmlString) |
Loads an XML document, |
save (objTarget) | Saves XML document to file |
abort | Interruption of the process of loading and processing the document. |
createAttribute (name) | Creates a new attribute with the specified name for the current element. |
createNode (Type, name, nameSpaceURI) | Creates a node of the specified type and name |
createElement (tagName) | Creates a document element with the specified name. |
createTextNode (data) | Creates text within a document |
getElementsByTagName (tagname) | Returns a reference to the collection of document elements with the given name |
nodeFromID (idString) | Find an element by ID |
XMLDOMNode object | |
An XMLDOMNode object that implements the underlying DOM interface Node, is intended for manipulating with a separate node of the document tree. Its properties and methods allow you to get and change complete information about the current node - its type, name, full name, its contents, list of child elements, etc. | |
Properties | |
nodeName, baseName | Returns the name of the current node. |
prefix | Returns the Namespace prefix. |
dataType | Specifies the content type of the current node |
nodeType, nodeTypeString | Returns the type of the current node: |
attributes | Gets a list of the attributes of the current node as an XMLDOMNamedNodeMap collection. |
text | Returns the contents of the current subtree as text |
xml | Returns an XML representation of the current subtree. |
nodeValue | Returns the contents of the current node. |
childNodes | Returns a list of child elements as XMLDOMNodeList. |
firstChild, lastChild | Returns the first / last child |
previousSibling, nextSibling | Returns the previous / next sibling. |
parentNode | Contains a link to the parent element. |
ownerDocument | Returns a pointer to the document containing the current node. |
Methods | |
appendChild (newChild) | Adds a new child to the current node. |
insertBefore (newChild, refChild) | Inserts a child node, positioning it in the current subtree to the left of the node specified by refChild. |
cloneNode (deep) | Creates a copy of the current item. |
getAttribute(name) getAttributeNode(name) setAttribute (name, value) setAttributeNode (XMLDOMAttribute) |
Access to attributes (create, read, write) of the object. Name is the name of the attribute, value is its value. Returns the value of an XMLDOMAttribute object. |
replaceChild (newChild, oldChild) removeChild (oldChild) | Replacing the oldChild object of the current list of child objects with newChild. Deleting oldChild object |
selectNodes (patternString) selectSingleNode (patternString) | Returns an XMLDOMNodeList object selected by search pattern or the first node |
transformNode (stylesheet) transformNodeToObject (stylesheet, outputObject) |
Assigns a style sheet to the subtree of the current node and returns a string that is the result of processing. The parameter is a reference to the DOMDocument object that contains the XSL statements. |
Using XML in business.
For a clearer picture, an explanation is needed, and why all this is needed in order to understand how it works:
When building a B2B or corporate ERP system, when organizing information exchange of XML documents between enterprises or branches of the pr-I, an efficiently proven system of information transfer based on existing WEB servers over HTTP protocols is used.
On the one hand, the application acts as a client, which issues an HTTP request in POST mode; on the other hand, there is a WEB server, on the side of which the request is processed and a response is issued. XML documents are used as an exchange.
For example, in a simple corporate ERP system, an accounting program (ACS Accounting), it is necessary to generate a request for an invoice and send it to a branch that has a warehouse (ACS Warehouse). AWP A similar problem statement when creating a B2B system, when Enterprise A requests the availability of products (makes an order for the purchase) from Supplier B.
Enterprise A and its program act as a client. The warehouse is served by Supplier B, who has a warehouse complex with a database on a SQL server. The exchange is carried out through the corporate WEB server of the Supplier V.
Below is the following typical exchange algorithm:
Figure 3.
- Enterprise A initiates process A(product order), which acts as a WEB client.
- Process A generates an XML document (for example, an invoice request) and transmits it as a POST http request to the WEB server of Provider B. The resource identifier of the processing application is used as a URI. The URI can be the same for all types of documents, or individual for each type. It all depends on the structure of the B2B (WEB) server.
- WEB server analyzes the request and generates a server Process B by passing the body of the XML document as a parameter.
Process B is launched by the WEB-server and is processed either as an ASP page, CGI (ISAPI) - application or JAVA server (server application) - Process B- generates a request to the SQL database server.
- The SQL server performs the necessary operations in the database, generates a response and returns it Process B.
- According to the response from the SQL server Process B generates an XML document (response) and returns it as a response to an http request to the client application.
- Further, depending on the situation on the client side, either a new http request is formed, or the session ends.
A few words about the organization of document flow.
The general rule for developing a system for exchanging XML documents is:
- At first- development of a flow chart of electronic documents and their structure;
- Secondly- development of tables of process functions (subprocesses), i.e. what function with respect to which XML document each process will implement.
Each XML document, like an HTML document, must consist of a message header (information enclosed by tags) and a message body (for a request, this information is framed with tags to respond to a request). In order for an XML document to be well formed, it is necessary to frame its two component parts "Title" and "Request" with tags, for example. The type of a typical document is presented below:
The header (Figure 4), in contrast to an HTML document, must contain various kinds of service information, including information about the type of the transmitted document and the process of its processing. The body of the document enters information processing, i.e. content framed by tags. It should be noted that the structure of headings should be the same for all types of documents.
For the Process launched by the server, it is preferable (but not necessary) to build the processing algorithm as follows:
Figure 6.
Some fundamental points when creating the client side
As already explained, when creating an XML document, its representation in the form of a DOM model is used. Below is an example of a Delphi text portion of a message xml header generating program.
procedure TThread1.HeaderCreate (Sender: Tobject); var // class declaration, needed to create coDoc: CoDomDocument; // XMLDomDocument object Doc: DomDocument; r: IXMLDOMElement; Node: IXMLDOMElement; // DOMText txt: IXMLDOMText; // DOMAttribute attr: IXMLDOMAttribute; begin // create DOM document Doc: = coDoc.Create; Doc.Set_async (false); // initial initiation of the DOM document Doc.LoadXML ("It should be noted that the declaration of the variable coDoc: CoDomDocument and Doc: DomDocument, as well as its creation by the Create (Doc: = coDoc.Create;) method, is done once. The variable declaration is located in the section describing global variables, and not in the local procedure, as it was demonstrated for clarity in this example (that is, one global variable of the DomDocument type per one program module).
The result of the work of the above program will be the created header, applied to our example xml-document: shown in Figure 5.
Figure 5.
Figure 6.
The main advantage of transferring information in the form of XML documents is that it is possible to form a message using independent table structures in the DBMS both on the receiving and transmitting sides. Using our example, suppose it is required to transfer information about the invoices of Enterprise A, from the DBMS having the structure shown in Figure 6
To generate an xml document containing an invoice, an SQL query (query A) is initially built with information about the invoice itself:
SELECT* FROM Invoice_General WHERE InvoiceNum =: num SELECT Goods, Qulity, Price, HZ_cod FROM Goods WHERE InvoiceNum =: num //: num is a parameter that specifies the invoice number.Below is a part of the program that generates the body of the xml document:
procedure TThread1.DataBodyCreate (Sender: Tobject); var // declaration of the class and the XMLDomDocument object// coDoc: CoDomDocument; // must be global for the whole module.// Doc: DomDocument; // declare DOMElement objects r: IXMLDOMElement; // DOMElement; Node, Node2: IXMLDOMElement; Node3, Node4: IXMLDOMElement; // DOMText txt: IXMLDOMText; str: String; // InvoiceNumber: integer;- global variable - // has the value 987654 // queryA, queryB: String;- a global variable, // has a value corresponding to the request // queryA - request A with general information about the invoice // queryB - request B information about the goods described in the // invoice (see text) begin Query.Close; // see the text "request A" Query.Text: = queryA; // execute the request Query.ExecSQL; Query.Open; // get the address of the root element r: = Doc.Get_documentElement; Node2: = Doc.createElement ("Request"); // create DOMElement (tag) Node: = Doc.createElement ("Invoice"); // add an element to the root r.appendChild (Node2); // add an item to Node2. appendChild (Node); // create DOMElement (tag) Node3: = Doc.createElement ("Depurture"); // add an item to Node. appendChild (Node3); // call to the "Depurture" field of the request str: = Query.FieldByName ("Depurture"). AsString; // create text node = field value// assign a value to the node // text node, variable str Node.appendChild (txt); // similar operations for the tagAs a result of this procedure, the following text of an XML document is generated:
To form a request, the Open method of the object is used IXMLHttpRequest:
procedure Open (const bstrMethod, - method type = "POST" bstrUrl, - Server url varAsync, - communication mode asynchronous / synchronous = true bstrUser, - username for authentication bstrPassword) - passwordCreating the server side of document processing
As noted earlier, processing an HTTP request can be handled by either CGI applications or Java servlets. The variant of writing ASP-pages is also possible. But in this case, data transfer is possible only by the "GET" method through the query string. However, handling an HTTP request for ASP pages is more efficient than a CGI application. However, in my opinion, it does not matter how to process it, but it is more important to solve the question - how to build a processing program, and not by what means.
If from the previous chapter we examined the options for forming an XML document, then the task of the server application is the opposite - parsing XML documents. Below is a part of the program that parses an xml document:
procedure Tthread1.DataParser (Sender: Tobject); var // declare DOMElement objects r, FNode: IXMLDOMElement; Str, Filename: String; parm: String; // soclass declaration and CoDocXML, CoDocXSL, CoDocResult: CoDomDocument; // XMLDomDocument object XMLDoc, XSLDoc, ResultDoc: DomDocument; // HttpStr: String; - a global variable containing the HTTP request string Begin XMLDoc: = coDocXML.Create; XMLDoc.LoadXML (HttpStr); // get the address of the root element r: = Doc.Get_documentElement; // get the value of the element FNode: = r.SelectSingleNode ("// TypeDocument"); // get the value of the attribute id = "Order" FileName: = FNode.GetAttibute ("id"); // and formation of the file name Order.xsl FileName: = FileName + ". Xsl"; // create XSLDoc document XSLDoc: = coDocXSL.Create; XSLDoc.LoadXML (FileName); // create XMLDoc document ResultDoc: = coDocResult.Create; // set synchronous processing mode ResultDoc.Set_async (false); // set parse check ResultDoc.validateOnParse: = true; // parsing XMLDoc using XSL template XMLDoc.transformNodeToObject (XSLDoc, ResultDoc); // the Str variable is assigned a text value // of the resulting document. Str: = ResultDoc.text; // find an element FNode: = r.SelectSingleNode ("// InvoiceNumber"); // and get the value of the element parm: = FNode.text; // close the request for access Query.Close; Query.Text: = Str; // assignment of parameter value Query.Params.AsString: = parm; // execute the request Query.ExecSQL; end;The whole highlight of the parsing lies in the use of an XSL template, which is individually generated for each type of document. The result of parsing is a SQL query string. Subsequently, the execution of the generated SQL query string will make the necessary changes to the data in the DBMS.
The advantage of using parsing through a template is also that you get some kind of data flexibility, and you get complete independence of the algorithm from the program code. Below is the text of the XSL template used to process a document of type ORDER:
Explaining the above example, it should be noted that the use of a pair of tags is formal in nature, since after parsing, the resulting XML document must formally contain at least one node. The ResultDoc.text method assigns the text value of the ResultDoc obtained during parsing of the XML document. In this case, the value is everything that is framed by a pair of tags and, i.e. the SQL query we have generated.
Another feature of writing a program should be noted the possibility of using the SQL parameter : num. Using the parameter simplifies the text of the xsl template. The definition of the value of the corresponding elements of the nodes of the XML document is determined initially by the selection by the name of the corresponding node, for example:
XSL at a glance
XSL is an acronym derived from eXtensible Stylesheet Language, a style sheet formatting language (XML data). As you can see from the header, eXtensible Stylesheet Language (XSL) is used to format XML data. By definition, the W3C XSL consists of two parts:
- XSLT - XSL Transformation. The language used to transform or format (transform) XML documents. Thus, with the help of XSLT, we can get different cuts of a set of data and forms of data presentation.
- Formatting elements. These elements include all the typographic elements of the data after they have been processed with XSL. Used only for generating HTML pages.
With the help of XSLT, we can select the data we need from an XML file, and arrange it in a form for presentation to the user. For example, in our case, we have transformed XML data in the form of a SQL query. The classic use of XSL is usually formatting data in the form of HTML pages or, more rarely, in the form of RTF files.
XSL file describes a template, according to which the transformation of XML data will be performed. Returning to xsl templates, the following elements (directives) can be distinguished in XSLT:
XSL directives | description |
---|---|
xsl: apply-templates | A directive indicating the use of matching templates for the select attribute = "template name" |
xsl: attribute | creates an attribute tree and adds it to the output element, parameter name = "attribute name", namespace is the namespace URI (namespace prefix) |
xsl: call-template | calls a template, attribute name = "URI to template" |
xsl: choose xsl: when xsl: otherwise |
selection by condition xsl: when expr = "evaluation of expression on script", language = "language-name" test = "evaluated expression" |
xsl: comment | generates a comment in the output document |
xsl: copy xsl: copy-of |
copies the current node to the output source or inserts a document fragment into a node where the select attribute = "source node name" |
xsl: element | creates an output element by name, attribute name = "element name", namespace = "uri namespace reference" |
xsl: for-each | reapplies the template to all nodes of the node list, the select attribute specifies the list of nodes |
xsl: if | condition check, set by the test attribute as an expression |
xsl: include | includes external template, attribute href = "URI reference" |
xsl: output | specifies the output, the method attribute can be "xml", "html", or "text" |
xsl: param | specifies the value of the parameters, attribute name = "parameter name", select = "value" |
xsl: processing-instruction | creates a processing instruction, attribute name = "name of the instruction process" |
xsl: sort | sorts set of nodes, attributes select = "node name", data-type = data type ("text" | "number" | Qname), order = sorting direction ("ascending" | "descending") |
xsl: stylesheet | defines an xsl template document, is the root element for XSLT |
xsl: template | defines an xsl-template, attribute name = "URI prefix to the template name", match = "an indication of the node to which the template is applied" |
xsl: text | generates text to the output stream, attribute disable-output-escaping = "yes" or "no", indicates the ability to generate ESC characters |
xsl: value-of | inserts the value of the selected node as text, attribute select = "pointer to node" from which the value is taken |
xsl: variable | specifies the value of variable bounds, attribute name = "variable name", select = "computation of variable value" |
xsl: with-param | applies parameter to template, attribute name = "parameter name", select = expression to evaluate the current context, default value "." |
Conclusion
Finally, it should be noted that using the standard XML parser msxml.dll is not the only tool for parsing and creating XML documents. For example, to create XML documents effectively use the components TPageProduser and TableProduser... But, this article only emphasizes the breadth and applicability of the DOM model in practice.
The author will be very grateful for your feedback on the relevance of the topic, general content, presentation style, as well as all other comments that will help to further improve the quality of writing a collection of articles and the release of a book covering the topic of the practical side of using XML documents in e-commerce. More detailed information on the practical side of the use of electronic documents can be found on the author's website www.eDocs.al.ru It is also planned to place the source texts and examples on the author's site.