The XML language is increasingly used to store information, sharing it between applications and Web nodes. In many applications, this language is used as a basic storage of data in others - to export and import XML data. It follows from this that it is time for developers to think about how to use XML data in your own applications.
In this article we will look at XML Document Object Model (DOM) and its implementation by Microsoft - Microsoft XML DOM.
The XML DOM is an object model that provides the developer objects to download and process XML files. The object model consists of the following main objects: XMLDOMDocument, Xmldomnodelist, Xmldomnode, XmldomnamedNodeMap and XMLDOMPARSEERROR. Each of these objects (except XMLDOMPARSEERROR) contains properties and methods to obtain information about the object, manipulate the values \u200b\u200band structure of the object, as well as move along the XML document structure.
Consider the main objects of XML DOM and give several examples of their use in Borland Delphi.
Using XML DOM in Borland Delphi
In order to use Microsoft XML DOM in Delphi applications, you must connect the appropriate type library to the project. To do this, we execute the Project | Import Type Library and in the Import Type Library dialog panel, select the Microsoft XML Version 2.0 library (Version 2.0), which is usually located in the Windows \\ System \\ MSXML.DLL file
After pressing 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 link to the MSXML_TLB module must be listed in the list of Uses.
XML DOM device
Document Object Model represents an XML document in the form of a tree structure consisting of branches. XML DOM software interfaces allow applications to navigate the document tree and manipulate its branches. Each branch can have a specific type (DomnodeType), according to which parent and subsidiaries are determined. In most XML documents, you can find branches of the Element, Attribute and Text branches. Attributes (attribute) are a special type of branch and are not subsidiary branches. Attribute management uses special methodsprovided by XML DOM objects.
In addition to implementing the recommended World Wide Web Consortium (W3C) interfaces, Microsoft XML DOM contains methods that support XSL, XSL Patterns, Namespaces and data types. For example, the SelectNodes method allows you to use XSL templates syntax (XSL Pattern Syntax) to search for branches at a specific context, and the TRANSFORMNODE method supports the use of XSL to perform transformations.
Test XML document
As an example of an XML document, take the catalog of music CD-ROM, which has the following structure:
Now we are ready to start considering the object model XML DOM, familiarity with which will start with the XMLDOMDocument object.
XML document - XMLDOMDocument object
Working with the XML document begins with its download. To do this, we use the LOAD method that has only one parameter indicating the URL of the downloaded document. When downloading files from a local disk, only the full file name is specified (File: /// protocol in this case can be omitted). If the XML document is stored as a string, the LoadXML method should be used to download such a document.
To control the method of downloading a document (synchronous or asynchronous), the ASYNC property is used. By default, this property is true, indicating that the document is loaded asynchronously and control is returned to the application even until the document is fully loaded. Otherwise, the document is loaded synchronously, and then you have to check the value of the READYSTATE property to find out, the document loaded or not. You can also create an OnReadyStateChange event handler that will receive control when changing the value of the READYSTATE property.
Below is shown how to download an XML document using the LOAD method:
Users ... MSXML_TLB ... Procedure TFORM1.Button1Click (Sender: Togject); VAR XMLDOC: IXMLDOMDocument; Begin xmldoc: \u003d codomdocument.create; Xmldoc.async: \u003d false; Xmldoc.load ('C: \\ Data \\ Data.xml'); // // Here is the code that manipulates // XML document and its branches // XMLDOC: \u003d nil; end;
After the document is loaded, we can refer to its properties. Thus, the NodeName property will contain the #Document value, the NodeTypeString property is a Document value, the URL property is the File: /// C: /Data/Data.xml value.
Processing is mistake
Of particular interest are the properties associated with the processing of the document when it is loaded. Thus, the ParsEerror property returns an XMLDOMPARSEERROrror object containing error information that occurred during the processing process.
To write an error handler, you can add the following code:
VAR Xmlerror: IXMLDOMPARSEERROR; ... xmldoc.load ('C: \\ Data \\ Data.xml'); Xmlerror: \u003d xmldoc.parseerror; If xmlerror.errorcode.<> 0 THEN // // Here we process the error // Else Memo1.Lines.add (xmldoc.xml); ... xmldoc: \u003d nil;
To find out which information is returned in case of error, change the following directory item:
removing the closing element
Now write the code that returns the properties of the XMLDOMPARSEERROrror object:
Xmlerror: \u003d 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 ('Row:' + inttostr (line)); Add ('Position:' + INTTOSTR (LINEPOS)); End else memo1.lines.add (xmldoc.xml); End;
and fulfill our application. As a result, we obtain the following error information.
As can be seen from the above example, the information returned by the XMLDomparseerror object is enough to localize the error and understand the reason for its occurrence.
Now restore the closing element
Access to the document tree
To access the document tree, you can either get the root element and then go through its subsidiaries, or find some specific branch. In the first case, we get the root element through the DocumentElement property, which returns an object of type XMLDOMNODE. Below is shown how to use the DocumentElement property in order to obtain the contents of each child element:
VAR NODE: ixmldomnode; Root: ixmldomelement; I: integer; ... root: \u003d xmldoc.documentElement; For i: \u003d 0 to root.childnodes.length-1 do begin node: \u003d root.childnodes.Item [i]; Memo1.Lines.add (Node.Text); End;
For our XML document, we get the following text.
If we are interested in some kind of specific branch or branch level below the first subsidiary, we can use either the NodeFromid method or the GeTElementByTagName method of the XMLDOMDocument object.
The nodefromid method requires specifying a unique identifier defined in XML Schema or Document Type Definition (DTD) and returns a branch with this identifier.
The GetElementByTagName method requires an indication of a string with a specific element (tag) and returns all branches with this item. Below is shown how to use this method to find all performers in our CD-ROM directory:
Nodes: ixmldomnodelist; Node: IXMLDOMNODE; ... nodes: \u003d xmldoc.getelementsbytagname ('artist'); For i: \u003d 0 to nodes.length-1 do begin node: \u003d nodes.Item [i]; Memo1.Lines.add (Node.Text); End;
For our XML document, we will get the following text.
Note that the XMLDOMNODE selectnodes method provides a more flexible way to access the branches of the document. But about it is slightly lower.
Document branch - XMLDOMNODE object
The XMLDOMNODE object is a document branch. We have already encountered this object when the root element of the document was obtained:
Root: \u003d xmldoc.documentElement;
To obtain information on the branch of the XML document, you can use the properties of the XMLDOMNODE object (Table 1).
To access data stored in the branch, usually use the NodeValue property (available for attributes, text branches, comments, instructions for processing and CDATA sections), or the Text property that returns the text content of the branch, or the NodeTypeDValue property. The latter, however, can only be used for branches with typed elements.
Moving on the document tree
The XMLDOMNode object provides a variety of ways to move through the document tree. For example, to access the parent branch, the ParentNode property is used, access to child branches is carried out through the Childnodes properties (XMLDCHILD type), FirstChild and Lastchild (type XMLDOMNODE), etc. The OwnerDocument property returns an XMLDOCUMENT object that identifies the XML document itself. The above properties make it easy to move through the document tree.
Now I will overcome all the branches of the XML document:
Root: \u003d xmldoc.documentElement; For i: \u003d 0 to root.childnodes.length-1 do begin node: \u003d root.childnodes.Item [i]; If node.haschildnodes then getchilds (node, 0); End;
As noted above, the selectnodes object XMLDOMNODE provides a more flexible way to access the branches of the document. In addition, there is a SELECTSINGLENDE method that returns only the first branch of the document. Both of these methods allow you to specify XSL templates to search for branches.
Consider the process of using the SELECTNODES method to extract all branches that have a CD branch and inflation.
Root: \u003d xmldoc.documentElement; Nodes: \u003d root.selectnodes ('CD / Price');
The NODES collection will be placed all switter Price CD branches. The discussion of XSL templates will return a little later.
Manipulation by daughter branches
For manipulation of subsidiaries, we can use the methods of the XMLDOMNode object (Table 2).
In order to completely delete the record of the first disk, you need to perform the following code:
VAR XMLDOC: IXMLDOMDocument; Root: ixmldomnode; Node: IXMLDOMNODE; Xmldoc: \u003d codomdocument.create; Xmldoc.async: \u003d false; Xmldoc.load ('C: \\ Data \\ Data.xml'); // Get the root element root: \u003d xmldoc.documentElement; Node: \u003d root; // Remove the first subsidiary node.Removechild (Node.firstchild);
Please note that in this example we remove the first subsidiary. How to remove the first element of the first subsidiary, is shown below:
VAR XMLDOC: IXMLDOMDocument; Root: ixmldomnode; Node: IXMLDOMNODE; Xmldoc: \u003d codomdocument.create; Xmldoc.async: \u003d false; Xmldoc.load ('C: \\ Data \\ Data.xml'); // Get the root element root: \u003d xmldoc.documentElement; // And the first subsidiary node: \u003d root.firstchild; // Remove the first subsidiary node.Removechild (Node.firstchild);
In the example above, we did not remove the first branch.
Now add a new branch. Below is a code showing how to add a new record of music CD-ROM:
Var Newnode: ixmldomnode; Child: ixmldomnode; ... // Create a new branch -
The above code shows the following sequence of actions to add a new branch:
- Creating a new branch using CreateNode:
- creating an item using the CreateNode method;
- adding an element to the branch by the APPENDCHILD method;
- setting the value of the element through the TEXT property;
- ... repeat for all items.
- Adding a new branch to the document by AppendChild.
Recall that the AppendChild method adds a branch at the end of a tree. To add a branch to a specific place of the tree, you need to use the InsertBefore method.
Set of branches - XMLDOMNODELIST object
The XMLNodelist object contains a list of branches that can be built using the SelectNodes or GetElementsByTagname methods, and is also obtained from the Childnodes property.
We have already considered the use of this object in the example given in the section "Moving on the document tree". Here we also give some theoretical comments.
The number of branches in the list can be obtained as the value of the Length property. The branches have indices from 0 to Length-1, and each individual branch is available through an Item array element with the corresponding index.
Moving on the list of branches can also be carried out using the NEXTNODE method returning the next branch in the list, or Nil, if the current branch is the latter. To return to the top of the list, you should call the Reset method.
Creating and saving documents
So, we looked at how you can add branches and elements to existing XML documents. Now create an XML document "on the fly". First of all, we will remind you that the document can be loaded not only from the URL, but also from the usual string. Below is shown how to create a root element, which can then be used to dynamically build the remaining elements (which we have already considered in the section "Manipulation of subsidiaries"):
VAR XMLDOC: IXMLDOMDocument; Root: ixmldomnode; Node: IXMLDOMNODE; S: WideString; ... S: \u003d '
After building an XML document, save it in the file using the SAVE method. For example:
Xmldoc.save ('C: \\ Data \\ NewCd.xml');
In addition to saving in the file, the SAVE method allows you to save an XML document in a new XMLDomDocument object. In this case, the document is full processing and, as a result, checking its structure and syntax. Below is shown how to save a document in another object:
Procedure TFORM1.Button2Click (Sender: Togject); VAR XMLDOC2: IXMLDOMDocument; Begin xmldoc2: \u003d codomdocument.create; Xmldoc.save (xmldoc2); Memo2.lines.add (xmldoc2.xml); ... xmldoc2: \u003d nil; end;
In conclusion, we note that the SAVE method also allows you to save an XML document to other COM objects that support iStream, IsetStream or IpescistStreaminit interfaces.
Using XSL templates
Discussing the XMLDOMNODE object selectnodes method, we mentioned that it provides a more flexible way to access the branches of the document. Flexibility lies in the fact that as a criterion to select branches, you can specify an XSL template. Such templates provide a powerful mechanism to search for information in XML documents. For example, in order to get a list of all the names of music CD-ROM in our directory, you can follow the following query:
To find out whether discs of which performers are released in the United States, the request is formed as follows:
Nodes: \u003d root.selectnodes ('CD / ARTIST');
Below is shown how to find the first disk in the directory:
Nodes: \u003d root.selectnodes ('CD / TITLE');
and last:
Nodes: \u003d root.selectnodes ('CD / TITLE');
To find the discs of Bob Dilan, you can perform the following query:
Nodes: \u003d root.selectnodes ('CD [$ any $ arst \u003d "bob dylan"] / title');
and to get a list of disks released after 1985, we carry out the following query:
Nodes: \u003d root.selectnodes ('CD / TITLE');
A more detailed discussion of XSL syntax requires a separate publication. To intrigue readers and push further research, I will give only one small example of the possible use of XSL. Suppose we need to convert our directory to the usual HTML table. Taking advantage of traditional ways, we must sort out all tree branches and for each item obtained to form the corresponding tags
Using XSL, we simply create a template (or style table), in which we indicate what and how to convert. Then we impose this template to our catalog - and ready: before us the text of the XSL template, which converts the directory in the table (Listing 2).
The code for overlaying the XSL template to our catalog looks like this:
Procedure TFORM1.Button2Click (Sender: Togject); VAR XSLDOC: IXMLDOMDocument; Begin Xsldoc: \u003d codomdocument.create; Xsldoc.load ('C: \\ Data \\ Data.xsl'); Memo2.Text: \u003d XMLDOC.TransFormNode (XSLDOC); Xsldoc: \u003d nil; end;
By completing our discussion of XSL, it should be said that currently this language is actively used for transformation between different XML documents, as well as for formatting documents.
Conclusion
For quite understandable reasons, in one article it is impossible to consider all Microsoft XML DOM objects and bring examples of their use. Here we only touched on the main issues of using XML DOM in applications. In tab. 3 shows all objects implemented in Microsoft XML DOM.
ComputerPress 12 "2000
Order Solving Tasks on Delphi
Delphi is the second programming language with which the students most often get acquainted in the learning process. This is the beginning of learning object-oriented programming. I, as a student, made for myself the conclusion that there is no easier method to master the language than to write a calculator on it. Even if you realize the elementary function of the addition of two numbers, this is already on a lot of light.
Codegaear, Delphi 7, Lazarus is different compilers, programs that will be transferred to the machine code written by you, converting it into zoliki and one. These are all programs for creating programs, and not separate programming languages. These compilers use the Object Pascal programming language underlying the Delphi language, which is similar to the syntax similar to the usual Pascal, but is functional significantly different.
What is programming language syntax?
This is a format for writing various operators. For example, the "For" cycle on the Pascal has the following format: "For n: \u003d 1 to k do", etc.
In the C ++ programming language, the same cycle is written somewhat differently: for (n \u003d 1; n We write a calculator
This will give you to understand how objects with the program code are interacting, what is "variables", how mathematical functions work. All programming in any case will be a calculation. The game is also a program that constantly considers something, works with numbers and numeric functions. Programming is inseparable from mathematics.
We use to write the Lazarus development environment. Its functionality is not as rich as, say, Codegear, but it is free access and is designed to study.
Opening the development environment, we see the shape and panel of the elements. Here is a form.
Here is the element panel.
The first thing we will do is add the three items you need to implement the addition function of two numbers. We need: "Tedit" in the number of three pieces and "tbutton". In the picture below, they are shown in the Arrows panel. Click on them once, and then once in shape, and they appear on it.
These are text fields for input and a regular button. You encounter these elements using almost any Windows program. Take a look.
Now clean these inscriptions. Click the View tab. And click on the "Inspector of Objects. This window will appear.
Click once on our element "Button" on the form and change the value "Caption" in the inspector window to any other. For example, on the word "OK". Click Enter. We see on the form, as the element has changed the name.
Just do it with Edit, just do not rename, but we will make them without any content. We highlight them in turn and clean the TEXT value in the inspector. Do not forget to press ENTER.
According to the result, our form looks like this.
Now that our calculator earned, you need to register the necessary software code for the procedure of our button. Click on the Button element twice and open the source editor.
See? Button1Click procedure. This is a procedure that is responsible for what happens when we click on the button once. And the following must occur: the program is needed in the third edit to bring us the sum of the numbers introduced in the first two fields. We write the code.
Such simple 5 lines of code we need to write. Comments and explanations are visible in the picture above. After that, click this button.
A compilation of our project will be compiled. It will be assembled in the program. We enter the numbers in the first two fields, click on the button and get the value of the amount.
Conclusion
You can click the "File" button, then "Save everything", select the folder to save and you will have a full-fledged program, the start of which can be done from the desktop. Now try to figure it out on your own that you need to rewrite in this code so that the program shall be divided by two numbers, and not folded. Tip: You need to change the data type. The video below shows a similar example, but in Delphi 7, not Lazarus.
Many Delphi programmers, Saving settings are associated using INI. Files in their programs. The use of this method, in less serious projects, it is necessary to avoid, as it limits in flexibility, which prevents further expansion of the program. It is worth saying that such an approach is quite popular, due to its ease of use and the presence of built-in funds on the development environment.
However, the ideal option for storing the program settings are structured Xml Files. Their advantage is that the number of parameters may not be fixed. To better understand this, consider a specific example.
In the USEarch program, when you click on recording, a context menu appears, which displays the list of points. These items are commands that in turn are downloaded from the settings file. In the event that the settings were stored in INI. The file, the program could save and load a certain number of commands, for example 10 or 50. As soon as you need more important, you will need to rewrite the code and, accordingly, re-compile it.
Applying an approach using Xml Files, we will have the ability to download all the parameters of the section dynamically. To all this, the configuration file will become more elegant, without excessive numbering of parameters. However, standard tools for working with Xml Delphi has many drawbacks, so I recommend using the standard library MSXML.. Usually it is the default part of the Windows family systems.
For connecting MSXML.We need to form an interface file with a list of all functions by importing it from the COM server. How to import the interface is written not enough detailed articles, I suggest you download the file MSXML2_TLB.PAS. Already ready to use. After the file is downloaded, place it next to your project, or throw to the Delphi Lib LIB folder. Thus, all programs created will be able to use the module. MSXML., It is enough to add msxml2_tlb to the USEs.
For clarity, consider the following example of the application of this library:
Procedure Loaddata; VAR XMLDOC: DomDocument; Root: ixmldomelement; Begin xmldoc: \u003d codomdocument.create; XMLDOC.LOAD ("settins.xml"); Root: \u003d xmldoc.documentElement; ShowMessage ("Size / Width"). Text); Root: \u003d nil; Xmldoc: \u003d nil; end;
First, an instance of the DomDocument class is created, after which the contents of the settings.xml file is loaded into the memory. As 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 contents of the content between tags
Here the SELECTSINGLENDE method is applied, which takes the string as a parameter.
Welcome! This blog is devoted to the Internet and computers, and, more precisely, they were dedicated to them.
Probably it is immediately seen that many years have not appeared on the site for many years. Yes, this is the fate of most blogs. Once this project was an ambitious undertaking, and the author, as in many others who wrote at the time, were large-scale plans to become one of the best Russian bloggers. Well, if you look now, then from those blogs that were created simultaneously with mine, most had already dissolved in eternity. And I tritely became missing time blog. So yes, it is no longer updated. Although I once won in this site in the 2011 Blog Competition.
I even had the idea to remove all this, but then I revised the old materials, and realized that they could still be useful to readers. Yes, some articles are outdated (if I have enough strength, they will receive the appropriate marks), but the site, for example, can be useful to beginners - here you can read about the basic concepts of the Internet, learn to customize the Internet, Windows or even decide to go to Linux. So look at the headings and select the one that is suitable for you.
And, after all, I hope it is more than just a blog, but a real Internet guide. The site can be found in the directory mode, where all available articles are structured by categories. And who knows maybe, new quality articles will begin to appear here.
Sander
Picodi.ru is a discount portal from International Coupons, a Polish expert in saving and cheap purchases. Poles are considered one of the most economical nations in the world, therefore it is not surprising that this type of project has grown from the Polish startup KODYRABATOWE.PL. What can be useful to this portal to an ordinary Internet user in Russia?
Modern android telephones are more than phones. You get used to the set of installed programs, to the history of your calls and text messages, collections of photos and a lot. But the time goes, and the fully arranged device starts to slow down, bug, or simply loses a presentable view because of the chipping on the body or scratches on the screen. There is a question of choosing a new phone and changing the Android phone. And if the question of choice, we will now bypass the party now, then "moving" to a new phone remains a serious problem - I absolutely do not want to start all the data from scratch. Here we will talk about this today.
Most of the readers of this blog, most likely, never faced versions of version control and will not come up in the near future. And sorry. This extremely user-friendly invention is widely used by programmers, but, in my opinion, it could be very useful and to those who actively work with the texts. But, probably, there is no version control system now, which it would be easy to start using for the "office" (Microsoft Office) of work. Nevertheless, I think that the material set forth in the article may be interesting for all readers.
If you thought about how from your TV watch movies over the network and access the Internet, this article is for you. No, I know that some TVs have the functionality of Smart TV, but I have never seen it work fine. Apparently, therefore, Google's recently demonstrated a completely stunning device, immediately ended with a sensation. We are talking about the media streamer Chromecast (chromkast), a more perfect and affordable version of last year's favored player Nexus Q.
Dongle Chromkast, the dimensions of which do not exceed 2 inches, connects to the HDMI port of the 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 IOS, Windows, Android or Mac OS operating platform.
This article is devoted to the Android system memory device, problems that may arise due to its lack and how to solve them. I myself did not have so long ago that my Android phone began to regularly issue messages about a shortage of memory when trying to establish a particular application. What was very strange for me despite the fact that on the description on the market there should have been about 16GB, and I also increased this volume using an additional memory card. However, the problem was, and I had to thoroughly tinker before I found the right solution that does not require the receipt of root access or the full recovery of the phone to the factory state.
Recently, much attention is paid to building e-business systems, or as they are also called - B2B (Business to Business). Given the recommendations on the construction of exchange streaming systems of coordinating Internet technologies of the body - WWW Consortium: emphasis is made towards XML technologies and building XML document exchange systems.
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 representation of structured information, the ability to use modern network protocols and creating real-time business systems.
Independence of the presentation of information in the form of XML documents allows different, participating in the electronic business, to produce independent from each other by.
In all systems, the exchange is usually built by the same scheme using HTTP requests. The SSL protocol is applied as the SSL protocol (but this is a separate topic).
One of the possible options for processing XML messages is to build BIN / CGI (ISAPI) -News or COM (server) components forming or processing XML documents.
On the one hand, the application acts as a client, which in POST mode issues an HTTP query, on the other hand, is a WEB server on the side of which the query processing and an answer is processed. The information exchange uses XML documents.
One of the most effective implementation options is the use of an existing XML parser supporting the DOM model. Such a parser is a distributive supply of Win`98 or an integral part of IE 4.7 and above (for Win`95) and represents the COM server located in the msxml.dll library.
The component object model (COM) is encapsulated data and methods into a single essence and a way to access them through the interface system. Delphi is simply accessible to access to the COM object classes (several classes may be included in one COM server). Access to objects is carried out by initializing the class instance through the interface system. Description of the interfaces is carried out by the interface definition language (IDL), which is possible to carry out the means of the medium automatically.
Delphi means Imports from the COM server msxml.dll.The IDL interface description files are built and the binary description file of the library type is TLB. This operation is carried out through the system menu: Project | Type Library Import:(picture 1). The following dialog box appears (Figure 2), in which you want to select a COM object (in our case, the object is registered as "Microsoft.xmldom (Version 2.0)") and create a TLB file (button Create Unit.). Using the TLB file, the environment generates "Paskalevsky" file description of the COM server - MSXML_TLB.PAS
The MSXML_TLB.PAS file describes all interfaces, constants and COM servers.
For access to the objects of the COM element, it is necessary in the directive Uses.add the name of the library description file (msxml_tlb.pas). Below is the simplest program that uses the DOM standard MSXML.dll analyzer, which downloads the XML document and displays it in the Memo1 text box element.
uses. Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs, Oleserver, MSXML_TLB, STDCTRLS; type TForm1 \u003d. class(TForm) Button1: Tbutton; Memo1: TMemo; procedure. Button1Click (Sender: Togject); end; var. Form1: TForm1; implementation ($ R * .dfm) Procedure.TForm1.Button1Click (Sender: Togject); // Declaration of Soklass object DomDocument; var.codoc: Codomdocument; // class, consistent with the iDomDocument interface; var.Doc: IXMLDOCUMENT; begin. // Creating an instance of the DomDocument object; Doc: \u003d Codoc.create; // call a mode method of an instance of the domdocument object; Doc.Load ("data.xml"); // Access to the XML property instance of the domdocument object; Memo1.Text: \u003d doc.xml; end; end.DOM Concept - Object Document Model
Each XML document is represented as a set of a plurality of objects (classes), with which access to individual elements (object fields) is possible. DOM - interface describes access to both simple domstring or characterdata objects and parts or separate XML elements of the document: DomfragmentElement, Domnode, Domelement.
The following are the most important properties and methods of XMLDomDocument, XMLDOMNODE, XMLDOMNODELIST. It should be noted that the MODEL MSXML.DLL XML analyzer, the MSXML.DLL XML analyzer, presented below, are used by the MSXML.DLL XML analyzer than the DOM Consortium approved by the W3C model.
A more complete description of the interface DOM objects can be found on
Xmldomdocument object | |
Represents the top level of the object hierarchy and contains methods for working with a document: its downloads, analysis, creating elements, attributes, comments in it, etc. . | |
Properties | |
Async. | Property Identifying Current Processing Mode |
Parseerror | Returns a reference to the XMLDOMPARSEERROR error processing 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 XMLDOMEMEMENT object. |
Methods | |
load (URL) loadXML (XMLString) |
Loads an XML document |
save (Objtarget) | Saves the XML document in the file |
aBORT. | Interrupting the process of downloading and processing the document. |
createAttribute (Name) | Creates a new attribute with the specified name for the current item. |
createNode (Type, Name, Namespaceuri) | Creates a node of the specified type and title |
createElement (TagName) | Creates a document element with the specified name. |
createTextNode (DATA) | Creates text inside the document |
getElementsBytagname (TagName) | Returns a link to the collection of document items with the specified name |
nodeFromid (idstring) | Search element by identifier |
XMLDOMNODE object | |
XMLDOMNODE object that implements the basic DOM interface Node., Designed to manipulate with a separate knot of a document tree. Its properties and methods allow you to receive and change full information about the current node - its type, name, full name, its contents, a list of child elements, etc. | |
Properties | |
nodeName, Basename. | Returns the name of the current node. |
prefix. | Returns the namespace prefix. |
datatype. | Defines the content type of the current node |
nodeType, NodeTypestring | Returns the type of the current node: |
attributes. | Returns a list of attributes of the current node as the XMLDOMNAMENDEMAP collection. |
tEXT. | Returns the contents of the current support in the form of text. |
xml | Returns the XML representation of the current support. |
nodeValue. | Returns the contents of the current node. |
childnodes. | Returns a list of child elements as xmldomnodelist. |
fIRSTILD, LASTCHILD. | Returns the first / last child element |
previousSibling, NextSibling | Returns the previous / next nursing element. |
parentnode. | Contains a reference to the parent element. |
ownerdocument | Returns the pointer to the document in which the current node is located. |
Methods | |
aPPENDCHILD (NEWCHILD) | Adds a new child element to the current node. |
iNSERTBEFORE (NEWCHILD, REFCHILD) | Inserts a child node, having it in the current subtree "left" of the node specified by the Refchild parameter. |
cloneNode (Deep) | Create a copy of the current element. |
getAttribute.(Name) getAttributeNode. (Name) setAttribute (Name, Value) setAttributeNode (XMLDOMAttribute) |
Access to attributes (creating, reading, writing) object. Name - Attribute Name, Value - its value. Returns the value of the XMLDOMAttribute object. |
replacechild (Newchild, OldChild) Removechild (OldChild) | Replacing the OLDCHILD object of the current list of subsidiaries on NewChild. Removing the OLDCHILD object |
selectNodes SELECTSINGLENDE (PATTERNSTRING) | Returns the XMLDOMNODELIST object selected by search pattern or first node |
tRANSFORMNODE (STYESHEET) transformNodetoBject (StyleSheet, OutputObject) |
Assigns a style table to support the current node and returns the string - the result of processing. A reference to the DomDocument object is transmitted as a parameter, in which the XSL instructions are located. |
Using XML in business.
For a clearer picture, an explanation is necessary, and why all this is necessary with what to understand how it works:
When building a B2B or corporate ERP system, when organizing an information exchange of XML documents between enterprises or branches of the Prom-I, an effectively proven information system is used on the basis of available Web servers on HTTP protocols.
On the one hand, the application acts as a client, which in POST mode issues an HTTP query, on the other hand, the WEB server is on the side of which the request is processed and the response. XML documents are used as exchanging.
For example, in a simple corporate ERP system of the accounting program (ACS accounting), it is necessary to form a certain request for an invoice and transfer it to a branch that has a warehouse (ACS Warehouse). ART is a similar setting of the problem when creating a B2B of the system, when an enterprise A requests the availability of products (makes an order for the purchase) from the supplier V.
Enterprise A and his program acts as a client. The warehouse serves the supplier in who has a warehouse bd complex on the SQL server. Exchange is carried out through a corporate web server 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) and transmits it as a POST HTTP query to a Web Supplier Server V. As an URI - a processing application identifier is used. URI may be the same as 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 the server Process B.By passing an XML document as a parameter.
The process in the web server is started and processed either as ASP page, CGI (ISAPI) - application or java Sevrlet (server application) - Process B.- Generates a request to the SQL database server.
- The SQL server makes the necessary operations in the database, forms the answer and returns it. Process B..
- On the answer from the SQL server Process B. Generates an XML document (answer) and lets it as an answer to the HTTP request to the client application.
- Further, depending on the situation on the client side, either a new HTTP query is formed, or the session ends.
A few words about the organization of document management.
The general rule of development of the XML exchange system is:
- firstly- development of the circuit of the flow of electronic documents and their structure;
- secondly- development of tables of functions of processes (subprocesses) i.e. What function in relation to which XML document will implement each process.
Each XML document, like an HTML document, should consist of a message header (information prisoner) and a message body (for the query this information framed by tagging to respond to the request). In order for the XML document to be correctly formed, it is necessary for its two components of the "header" and "request" to framed tags, for example. The view of the standard document is presented below:
The title (Figure 4), in contrast to the HTML of the document, should contain different kind of service information, including information about the type of document transmitted and processing process. The informational processing of the document is received, i.e. The meaningful part is framed by tag. It should be noted that the header structure should be united for all types of documents.
For the process running by the server, the processing algorithm is preferably (but not necessary) to build as follows:
Figure 6.
Some principal moments when creating a client part
As already explained, when creating an XML document uses its presentation in the form of a DOM model. Below is an example of the text of the Delphi text of the XML message header program.
procedure.Tthread1.HeaderCreate (Sender: Togject); var. // Classes Announcement is needed to create Codoc: Codomdocument; // XmldomDocument object Doc: DomDocument; R: ixmldomelement; Node: ixmldomelement; // Domtext TXT: IXMLDOMTEXT; // Domattribute ATTR: ixmldomattribute; begin. // Creating Dom Document Doc: \u003d Codoc.create; Doc.set_async (false); // initial initiation DOM document Doc.Loadxml ("It should be noted that the announcement of the CODOC: CodomDocument and Doc: DomDocument variable, as well as the creation of the Create method (doc: \u003d codoc.create;) is carried out once. The declaration of the variable is in the section of the description of global variables, and not in the local procedure, as demonstrated for visibility in this example (i.e. one global variable of the DomDocument type one program module).
The result of the above program will be the created header, in relation to our example of the XML document: depicted in Figure 5.
Figure 5.
Figure 6.
The main advantage of transmitting information in the form of XML documents is that it is possible to form a message using the independent structure of the tables in the DBMS both on the received and on the transmitted side. Using our example, let it be required to transfer information about the invoices of the enterprise A, from the DBMS of the structure shown in Figure 6
To form an XML document containing an invoice, an initially built SQL request (query a) with information about the Invoice:
SELECT * From invoice_general Where. InvoicEnum \u003d: Num SELECTGoods, quulity, Price, hz_cod From.Goods Where. InvoicEnum \u003d: Num //: Num - the parameter that specifies the invoice number.Below is part of the program forming the body of the XML document:
procedure. Tthread1.databodycreate (sender: tobject); var. // Classes and XmldomDocument // Codoc: Codomdocument; // must be global, for the entire module. // Doc: DomDocument; // Announcement of Domelement Objects R: ixmldomelement; // Domelement; Node, Node2: ixmldomelement; Node3, node4: ixmldomelement; // Domtext TXT: IXMLDOMTEXT; Str: String; // InvoicEnumber: integer; - Global variable - // Masching 987654 // Querya, QueryB: String; - Global variable, // Maintaining a request to request // Querya - request and general information on invoice // QueryB - Query B Information about the goods described in // Invoice (see Text) begin. Query.close; // See on the text "Request A" Query.Text: \u003d Querya; // Request execution Query.execsql; Query.open; // Get the address of the root element R: \u003d doc.get_documentElement; Node2: \u003d doc.createElement ("Request"); // Create Domelement (TAG) Node: \u003d Doc.CreateElement ("Invoice"); // Adding an item to the root R.APPENDCHILD (Node2); // Adding an item in Node2. AppendChild (Node); // Create Domelement (TAG) Node3: \u003d doc.createElement ("Depurture"); // Adding an item in Node. AppendChild (Node3); // Appeal to the "Depurture" field Str: \u003d Query.fieldByname ("Depurture"). Asstring; // Creating a text node \u003d field value // node assignment value // Text node, variable str Node.appendchild (TXT); // Similar operations for TagAs a result of this procedure, the following text of the XML document is formed:
The Open method is used to form a query. Ixmlhttprequest:
procedure. Open (Const Bstrmethod, - Method Type \u003d "POST" BSTRURL, - URL VARASYNC Server Address, - Asynchronous / Synchronous Communication Mode \u003d True Bstruser, - Username for BSTRPASSWORD authentication) - PasswordCreating a server part of document processing
As noted earlier, the processing of HTTP request can be carried out either CGI applications or Java servlets. Possible options for writing ASP pages. But in this case, data transmission is possible only by the "Get" using the query string. Although, the HTTP processing of the ASP page request works more efficiently than the CGI application. However, in my opinion, without any difference, how to process, and more importantly to solve the question - how to build a processing program, and not with what means.
If we reviewed an XML document formation options from the previous chapter, then the task of the server application is the opposite of XML documents. Below is part of the program that analyzes the XML document:
procedure.Tthread1.dataparser (sender: tobject); var. // Announcement of Domelement Objects R, Fnode: ixmldomelement; Str, FileName: String; Parm: String; // Soklass announcement and CodocXML, CodocxSl, Codocresult: Codomdocument; // XmldomDocument object XMLDOC, XSLDOC, ResultDoc: DomDocument; // httpstr: string; - A global variable containing the HTTP query string Begin. Xmldoc: \u003d codocxml.create; Xmldoc.Loadxml (httpstr); // Get the address of the root element R: \u003d doc.get_documentElement; // Obtaining the value of the element Fnode: \u003d R.SelectSinglenode ("// TypeDocument"); // Get an attribute value id \u003d "Order" FileName: \u003d Fnode.getAttiBute ("id"); // And forming the file name Order.xsl FileName: \u003d FileName + ". XSL"; // Creating a document XSLDOC Xsldoc: \u003d codocxsl.create; Xsldoc.loadXML (FileName); // Creating an XMLDOC document Resultdoc: \u003d codocresult.create; // Setting the synchronous processing mode Resultdoc.set_async (false); // Installing Debuting Check Resultdoc.validateonparase: \u003d true; // Collapse XMLDOC by XSL template XMLDOC.TransFormNoC, ResultDoc (XSLDOC, ResultDoc); // variable STR is assigned to text value // Resulting Document. STR: \u003d resultdoc.text; // Search element Fnode: \u003d R.Selectsinglenode ("// InvoicEnumber"); // and getting the value of the element Parm: \u003d Fnode.Text; // Closes access request Query.close; Query.Text: \u003d STR; // Assigning the value of the parameter Query.params.asstring: \u003d PARM; // Request execution Query.execsql; end;The entire range of parsing is to apply the XSL template, which is formed for each type of document individually. The analysis result is the SQL query string. In consequence, the execution of the generated SQL query string will make the necessary changes in the DBMS.
The advantage of using parsing through the template is also in the fact that it turns out some data flexibility, and the complete independence of the operation of the algorithm from the program code is obtained. Below is the text of the XSL template as used for processing document type.
Explaning the above example, it should be noted that the use of pairs of tags and is formal, because After parsing, at least one node should be present in the resulting XML document. The resultdoc.Text method assigns the text value obtained during the analysis of the XML document ResultDoc. In this case, the value is all that the pairs of tags are framed and, i.e. We have formed a SQL request.
Another feature of writing the program should be noted the possibility of using the SQL parameter : num. Using the parameter allows you to simplify the text of the XSL template. Definition The value of the corresponding elements of the XML document nodes is determined initially selecting the name of the corresponding node, for example:
Briefly about xsl
XSL abbreviation comes from Extensible Stylesheet Language - style table formatting language (XML data). As it is clear from the Extensible StyleSheet Language (XSL) header (XSL) is used to format XML data. By definition of W3C XSL consists of two parts:
- XSLT - XSL Transformation. The language used to convert or format (transform) XML documents. Thus, using XSLT, we can get different sections of multiple data and data presentation forms.
- Formatting elements. These elements include all elements of typographical data design, after they are processed using XSL. Used only to form HTML pages.
Using XSLT, we can select the data from the XML file you need, and arrange them in the form to provide the user. For example, in our case, we transformed XML data as a SQL query. The classic XSL application is usually formatting data as an HTML pages or a rare representation in the form of RTF files.
XSL file describes the template (Template), according to which the XML data conversion will be performed. Returning to XSL templates, the following elements can be allocated in XSLT (directives):
XSL directive | description |
---|---|
xSL: Apply-Templates | Directive, indicating the application of the appropriate templates attribute SELECT \u003d "Template name" |
xSL: attribute. | creates the attribute tree and adds it to the output element, the Name \u003d "attribute name" parameter, namespace - URI on the namespace (namespace prefix) |
xSL: Call-Template | causes a template, attribute Name \u003d "URI on the template" |
xSL: Choose. xSL: WHEN. xSL: Otherwise. |
making a selection by condition XSL: WHEN EXPR \u003d "Calculating expression on Script", language \u003d "Language-Name" test \u003d "Calculated expression" |
xSL: comment | generates a comment on the output document |
xSL: Copy. xSL: Copy-of |
copies the current node in the output source or inserts the document fragment to the node where the select \u003d "Name of the source node" attribute |
xSL: Element. | creates an output element by name, attribute Name \u003d "element name", namespace \u003d "URI reference to the namespace" |
xsl: for-each | re-apply template to all nodes list nodes, SELECT attribute sets a list of nodes. |
xSL: if. | conditions check is set by the TEST attribute as an expression |
xSL: include | includes an external template, attribute HREF \u003d "URI REFERENCE" |
xSL: Output | specifies the output result, the Method attribute may have "XML", "HTML" or "Text" |
xSL: Param | specifies the parameter value, the name \u003d "parameter name" attribute, select \u003d "value" |
xSL: PROCESSING-INSTRUCTION | creates instructions for processing, attribute Name \u003d "Name Process Instructions" |
xSL: Sort. | sorts many nodes, attributes select \u003d "node name", data-type \u003d data type ("text" | "Number" | qname), Order \u003d Sort direction ("Ascending" | "Descending") |
xSL: StyleSheet. | defines the XSL template document, is the root element for XSLT |
xSL: Template. | specifies the XSL template, the Name \u003d "URI prefix attribute to the template name", match \u003d "Note to the node to which the template applies" |
xSL: TEXT. | generates text to output stream, the disable-output-escaping \u003d "yes" or "no" attribute indicates the ability to generate ESC characters |
xSL: Value-of | inserts the value of the selected node as the text, the SELECT \u003d "pointer to the node" attribute from which the value is taken |
xSL: variable | specifies the value of the variable boundaries, the Name attribute \u003d "variable name", SELECT \u003d "Calculate the value of the variable" |
xSL: WITH-PARAM | applies the parameter to the template, the name attribute \u003d "parameter name", SELECT \u003d expression to calculate the current context, the default value "." |
Conclusion
In conclusion, it should be noted that using the standard XML parser msxml.dll.it is not the only means of parsing and creating XML documents. For example, to create XML documents to effectively use components TPageProduser.and TTableProduser.. But this article only emphasizes the breadth and possibility of applying a DOM model in practice.
The author will be very grateful for feedback on the relevance of the topic, the overall content, style of presentation, as well as all the other comments that will help further improve the quality of writing a collection of articles and the release of books that covers the subject of the practical side of the use of XML documents in e-commerce. For more information on the practical side of the application of electronic documents, you can learn from www.edocs.al.ru on the author's website, it is also planned to place source texts and examples.