Examples of xml files of 440 items. Example of an XML schema. XML Schema is an industry standard for describing XML documents

Sometimes understanding the XML file sent to the cadastral chamber is simply necessary when you feel that something needs to be corrected somewhere, and many people have a developed natural curiosity. But... Important. Remember that after signing the digital signature file, you cannot edit the XML file! As an example from practice, when dividing a plot into 300 memory units, a girl accidentally erased just one line in the address of one of the plots. And that's it... The XML file did not pass verification. Searching through all the entries in the program seemed tedious to me, especially since I knew what to look for. Having opened the XLM file in the test editor by searching, I found the required line and made changes. But again, I repeat - if you edited the file, then you need to re-sign it with your digital signature. So let's get started. I will present drawings and write descriptions for them.

And one more retreat, for editing and convenient viewing of XML files I recommend using the program. It will allow you to see the structure of the file and conveniently colorize it by values. For example, I’ll take an electric heated towel rail for the bathroom, well, of course, not his -), but an XML file for the formation of 2 memory units by allocating a share in the right of common ownership to a memory device with a cadastral number….
As an example, I'll first show a picture of a collapsed XML file with one collapsed block.

So, judging by the line counter located on the left, we have a file of 336 lines. As can be seen from the figure, the block Collapsed, plus icon on the right. Therefore, I will first describe line by line what is visible from this figure, and then we will analyze the blocks included in the block Because it is the most voluminous.

We will not consider the entire file line by line, but will consider only those lines in which our data is entered.

3 line : CodeType=”014″ – type of work, there are only two of them, as in our case – education and “015” – clarification. Version=”03″ – XML file version. GUID (Globally Unique Identifier) ​​is a statistically unique 128-bit identifier; in our case, the file name must match this indicator.
4 line : Data from the organization in which the cadastral engineer works, or data from the cadastral engineer himself.
5 line : Code of the recipient organization, in this case the Office of the Federal Service for State Registration, Cadastre and Cartography for the Republic of Tatarstan.

Now let’s immediately go to the end of the file, based on the presented figure, and look at the block . In this block, information about the cadastral engineer who performed the work is entered. Next comes the block where the coordinate system fits in. By the way "in text values ​​of a file, they are indicated by quotation marks.

In principle, opening a file in Notepad++, the entire structure of the XML file becomes clear. – Location – contains the address. Value in written when part of the address is missing from KLADR.

An example of a plan map XML file generated in the Polygon Map plan software product

To view this fragment more clearly, copy it and view it in the Notepad++ test editor, which you can download from the section

By mistaking the means for the end, people become disappointed in themselves and others, as a result of which nothing comes of all their activities, or the opposite of what they strived for comes out.I. Goethe

This chapter will show you how to write XML schemas. You will also learn that diagrams can be written in different ways.

XML document

Let's look at the following XML document called "shiporder.xml":

John Smith Ola Nordmann

Langgt 23
4000 Stavanger Norway Empire Burlesque Special Edition 1 10.90 Hide your heart 1 9.90

The above XML document consists of a root element shiporder with required attribute orderid . Element shiporder contains three child elements: orderperson, shipto And item. Element item is used twice and contains the element title, optional element note, as well as elements quantity And price.

Line xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells the XML parser that this document should be checked against the schema. Line xsi:noNamespaceSchemaLocation="shiporder.xsd" indicates where exactly the schema is located (in this case it is in the same folder as the "shiporder.xml" file).

Creating an XML Schema

Now let's create an XML schema for the above XML document.

Let's create a new file, which we will call "shiporder.xsd". To create an XML schema, we will simply follow the structure of the XML document and define each element we encounter. Let's start with a standard XML declaration, followed by a description of the element xs:schema , which defines the scheme itself:

...

Here we use the standard namespace ( xs ) and the URI associated with that namespace, which has the standard meaning http://www.w3.org/2001/XMLSchema .

Now we need to define the element shiporder. This element has an attribute and it contains other elements, so we treat it as an element of a composite type. Element child element definitions shiporder we will put it in the declaration xs:sequence , which specifies a rigid sequence of subelements:

...

Now let's define the element orderperson, which will be of simple type (since it does not contain any attributes or other elements). Its type ( xs:string ) is prefixed with the namespace associated with the XML schema, which indicates the use of a predefined data type:

Now we need to define: shipto And item. Let's start with the element definition shipto:

With the help of diagrams we can identify any element. Attributes will help us with this maxOccurs And minOccurs . Attribute maxOccurs specifies the maximum number of occurrences of an element, and the attribute minOccurs specifies the minimum number of occurrences. The default value for both attributes is 1.

Now let's define the element item. This element can be used an unlimited number of times within an element shiporder. Determine such a feature of an element item allows assignment to an attribute maxOccurs values "unbound" . This means that the element item can be used as many times as the author of the document needs. Please note that the element note optional. Let's define this by setting the attribute minOccurs to zero:

Now we can declare the element attribute shiporder. Since this is a required attribute, we use the definition use="required" .

Note: Attributes must always be declared last:

Here is the complete code for the schema file "shiporder.xsd":

Schema division

The previous method of arranging a diagram is very simple, however, when the document is quite complex, with this method the corresponding diagram can turn out to be quite cumbersome, which will greatly affect the ease of its reading and maintenance.

The next way to layout a diagram is to first define all the elements and attributes, and then link to these definitions using the attribute ref .

Below is the new layout of the schematic file ("shiporder.xsd"):

Using Named Types

A third way to layout a diagram involves defining classes or types that allow element definitions to be reused. This becomes possible by giving names to the elements simpleTypes And complexTypes , and then point to them using the attribute type .

The third way to layout the schematic file ("shiporder.xsd"):

Element restriction indicates that the data type is derived from data types in the W3C XML Schema namespace. So the following code snippet means that the value of the element or attribute must be a string:

However, much more often the element restriction used to place restrictions on elements. Look at the following lines from the diagram above:

This code snippet specifies that the value of an element or attribute must be a string, exactly six characters in length, and those characters must be the numbers 0 through 9.

1. Introduction

If any of you have ever tried to learn XML on your own, you may have encountered many of the same confusing concepts that I encountered in the past. DTD, XML Schema, namespaces, XPath, XPointers, XSL, XSLT, DOM, SAX, SOAP, I give up. I will only add that most of these materials are based on implementations, the code of which may contain errors. There are probably millions of ways to implement and use XML, but they can all be quite complex. And you know, XML can be very simple. If we forget about DTD, XML Schemas, namespaces, etc.
In an effort to quickly teach you how to work with XML, I will, if possible, ignore a decent amount of information that you can already read in the relevant literature. And the first thing I'm going to ignore is namespaces and schemas. This may seem strange to you, since most books start by explaining these concepts, but try to think of XML as a means to solve a specific problem, like a hammer. Do you really need to know how to build a house to use a hammer? What if all I need is to just hammer in a nail to hang a picture on? It's the same with XML, it can be very complex, generic enough to be used in hundreds if not thousands of applications, and very simple if you don't pay attention to a few things. In this article, I will focus on solving specific problems using XML.
So what exactly is the problem? Let's assume that I want to describe a simple object, such as a glass, using XML. Why am I going to use XML for this? Well, first of all, that's exactly what XML is designed for. XML describes the data. In my example, the glass is the data. In real life, data can be Word documents, spreadsheets, images, a book, a database record, or even C++ or Visual Basic classes. Secondly, XML is extensible. XML allows me to create as many features as necessary to describe the data, and these features will be whatever I want. And finally, because XML is quickly becoming a standard. If there is life on Mars, then you can be sure that they will be able to understand my XML file there.

What basic properties allow us to describe a glass?

What would the same thing look like in XML format?

glass 6 16 ice cube straw water yes

Notice that the first line of the file () has a special look for now, just remember that it should be here. The beauty of the XML format is that anyone can understand what it says just by looking at it closely. It is also clear that this is not the only possible XML description of the glass. If I ask 10 people to develop an XML description of a glass with the same properties, they will probably all create different but correct descriptions. This is where the problem lies. Perhaps not for us humans, but when a computer reads an XML file, it would be a great idea to let it know what the file is about. This is where namespaces and schemes come into play. Simply put, schemas are used to define an adequate structure for an XML file.
Now it's time to talk about a few simple XML rules that you need to follow:

XML Rule #1: A valid XML file must exactly match its schema. But for ease of understanding of the material, none of my examples will use diagrams. So, strictly speaking, none of my examples are "adequate". But honestly, I don't care. I'm not going to build a house, I just need to hang a picture. I'll talk more about this later when we discuss the XML Document Object Model.

XML Rule #2 Note: If you program in VB, remember: XML is case sensitive. XML is case sensitive. XML is case sensitive. XML is case sensitive. Write this sentence 1000 times and you will never forget.

XML Rule #3: Tags are usually called elements and each opening tag must have a corresponding closing tag. Following this rule, you will get a correct XML file. This is very important because until the XML file is formatted correctly, it will not be parsed and loaded into the Document Object Model. Note that if the element does not contain values ​​and does not contain other (nested) elements, the closing tag may look like instead of a more bulky design . You can see this approach in the previous example ( ).

XML Rule #4: Elements can contain attributes, and attribute values ​​must be enclosed in quotation marks (single or double).

XML Rule #5: You can use attribute names multiple times, but element names must be unique throughout the file. In the previous example, the qty attribute had a different meaning depending on which element it was used in ,, or . The meaning of an attribute depends on the context of its use. Whereas the value of an element always means the same thing, no matter where in the file the attribute is located. In the previous example, the element And always has the same meaning throughout our document. for example, always used to describe the height of a glass.

XML Rule #6: There are several special characters in XML that cannot be used directly because they are reserved in the XML syntax. Therefore, to use such characters, you will have to use a reserved construction starting with the & character and a special code, (the & character must be written as &) (the " character must be written as ") (the character< должен писаться как <) (символ >must be written as >) and (the " symbol must be written as "). Instead, you can also use the instruction, where "...." can be any sequence of characters except "]]>". This construction can appear anywhere, but it cannot be nested.

2. XML Document Object Model

The XML Document Object Model allows programmers to load the contents of an XML file into memory. Once an XML file is loaded in this way, it can be manipulated using the properties, methods, and events of the Document Object Model. This is where XML comes in handy. The Document Object Model greatly facilitates the retrieval and processing of XML file information. I will not talk here about all the capabilities of the document object model; I will only talk about some of the main features that will help achieve the goal of this article. I'll take the XML file I just created describing the glass, load it into the Document Object Model, and do a few things with it. I will save the remaining features and capabilities of the document object model for the next article, which talks about client XML. Note that although the document object model is very good and convenient for developers, it requires a fairly significant amount of system resources. Therefore, there is another method for parsing XML files, known as SAX. My article does not claim to be an exhaustive source of information on this issue, so it would be useful to also use the XML SDK.

Let's look at an example using Microsoft's XML parser version 3.0 (msxml3.dll) to understand how it all works. If you do not have an analyzer, the latest version can be downloaded from the Microsoft website.
Let's say I saved an example of a cup description in XML format in the file "http://web_server/xml/cup.xml" (local path C:\inetpub\wwwroot\xml\cup.xml) and now I want to load it into the document object model . The following code assumes that the analyzer is already loaded and running.

Visual Basic 6.0 code:(establish connection with Microsoft XML, v3.0) Dim xmlDoc as MSXML2.DOMDocument30 Set xmlDoc = New DOMDocument30 xmlDoc.async = False xmlDoc.validateOnParse = False xmlDoc.load ("c:\inetpub\wwwroot\xml\cup.xml" ) msgBox xmlDoc.xml ASP Server-Side code in Visual Basic: Dim xmlDoc Set xmlDoc = Server.CreateObject("Msxml2.DOMDocument.3.0") xmlDoc.async = False xmlDoc.validateOnParse = False xmlDoc.load "/xml/cup.xml" ASP Server-Side code in Java Script: var xmlDoc = Server.CreateObject("Msxml2.DOMDocument.3.0"); xmlDoc.async = false; xmlDoc.validateOnParse = false; xmlDoc.load("/xml/cup.xml");

Explanation of the above code - let's go through the VB6 code

Line 1: Dim xmlDoc as MSXML2.DOMDocument30

In this first line we define a reference to "Microsoft XML, v3.0". In this line I defined the xmlDoc variable as a reference to the XML document. MSXML2 is a library (use that name, don't try to write MSXML3, it won't work). DOMDocument30 defines an XML document object corresponding to version 3.0. You may also see this code: dim xmlDoc as MSXML2.DOMDocument. This construction is usually used when you do not want to specify a specific version of the XML document. In this case, the default analyzer registered in the system will be used. The only problem may be that the version of the analyzer registered by default may differ on different computers. If you want to be sure that the code you write will work with any version of the analyzer, then do not use constructs that are specific to specific versions of the analyzer. Because there is no guarantee that the user who will use your code will have the same version of the analyzer installed for which you wrote your code. Another advantage of developing code that is version independent of the analyzer is that when a newer version of the analyzer is released, it will be backward compatible with previous versions, and you will not have to recompile your code.

Line 2: Set xmlDoc = new DOMDocument30

This line initializes the xmlDoc variable as a new instance of the version 3.0 XML document object.

Line 3: xmlDoc.async = False

XML files can be loaded either synchronously or asynchronously. If xmlDoc.async = False, it means that the contents of the XML file will be loaded, and only after that control will be transferred to the calling process. If xmlDoc.async = True, it means that control will be transferred to the calling process immediately, without waiting until the contents of the XML file are completely loaded.

Line 4: xmlDoc.validateOnParse = False

This code indicates that the parser should not validate the XML file being loaded against its schema (validateOnParse = False). In order to enable schema compliance checking, you need to write validateOnParse = True.

Line 5: xmlDoc.load("C:\inetpub\wwwroot\xml\cup.xml")

This line calls a method to load the specified XML file. There are two kinds of loading method. The first one, which is written on line 5, loads the file into the document object model, and it is necessary to pass the full path to the XML file. The second loading option involves passing an xml string as a parameter. This type of loading could be called, for example, like this: xmlDoc.loadXML("valid xml string"). I'll show you how to use this method later.

Line 6: MsgBox xmlDoc.xml

This line displays the contents of the downloaded XML file. As a result, we should receive the original XML file that we created earlier.

2.2. Exploring the XML Document Object Model

Create a new project in Visual Basic and name it standard.exe. Paste the above code into your project's main window load method. Make sure you declare the reference to "Microsoft XML v3.0". To do this, click Project-->References, then scroll down the list that appears and find the desired link in it. Please note that the analyzer version 3.0 must be installed on your computer, otherwise it will not be listed. Set breakpoints on the last line of code (msgbox xmlDoc.xml). Run the application in debug mode. When the execution process reaches a stopping point, call the "Locals" window and look at the document object model. You can learn a lot by viewing what is displayed in this window. The "Locals" window should look similar to the image below. Here are some interesting properties of the Document Object Model.

The XML document object model always contains two top-level nodes:

  • Item1 is the root of the document elements branch (ignore it)
  • Item2 is actually the first element of the document (remember this)

nodeName or baseName - can be used when searching for the name of an element or attribute.
nodeType - use to get the type of the current node.
nodeValue - used to find out the value of node data.
childNodes is a collection of child nodes. They can be element nodes, text nodes, and CDATA nodes. There may be other types of nodes, which I won’t talk about now, but you can learn all about them in the XML SDK.
attributes is a collection of attribute nodes for the current element.
length - used to determine the number of nodes in the tree directly belonging to the current one.
xml - this property is present in all nodes and can be used to represent the current position in the document. The XML string starts at the current node and goes down to the end of the tree. This is a very useful feature. Experiment with it and see what happens.

2.2.2. Element nodes

An element node can contain child nodes of elements, attributes, text, or CDATA. From the figure below you can see the following information about the "SOLID" node:

nodeType - Current node type = NODE_ELEMENT - i.e. the current node is an element.
nodeName or baseName or tagName - Name of the current node (element) = SOLID.
Its parent element CONTENTS has 4 children.
This can be seen in the following figure, but SOLID has one child which is a text data type.
text - "ice cube" is a shortcut method that allows you to get the value of the current node without moving to a child text node.

2.2.3. Attribute Nodes

Attribute nodes can only consist of text or CDATA child nodes. The following figure shows what information can be obtained about node "qty":

nodeType - Type of the current node = NODE_ATTRIBUTE - the current node is an attribute.
nodeName or baseName - Name of the current node (Attributes) = qty

From the following figure it is also clear that qty has one child, which has a text data type.
text or value - "2" is a shortcut method that allows you to get the value of the current node without moving to a child text node.

2.2.4. Text and CDATA nodes

Text or CDATA nodes have no children. Text nodes contain the processed text data of their parent node. CDATA contains the raw text data of its parent node. CDATA nodes are created when data in an XML file is framed in a special way. The CDATA label tells the parser not to parse the data and to accept the characters inside the label as data. The CDATA section is especially useful when you need to insert code inside an XML file. The following figure shows what information can be obtained from the current text node:

nodeType - Type of the current node = NODE_TEXT - the current node contains text data.
nodeName - Name of the current node (text) = #text - all text nodes are called #text
data or text or value - "2" is the current node data.

2.2.5. Errors when loading a document

The parseError section of the document object model can be useful in identifying problems that arise when loading an XML document. If I remove the closing tag from OTHER in our example file and try to run the program again, I will get the following result. The first piece of useful information is that our nextSibling now contains the value Nothing. Now, if you look at childNodes, you can see that the length field is now 0. Both of these signs indicate that our XML document was not loaded. To figure out why, I open the parseError node and get all the error information.

So I've shown you how to load an XML file into the Document Object Model, but what do you do with it there? One of the main features that you can use is to perform various queries on an XML document. To do this, you can of course look through the entire document until you find the information you are looking for. But the most preferred way is to use one of two methods of the DOMDocument class. The two methods used to find the nodes in our previous example could look like xmlDoc.SelectSingleNode(patternString) to get the node we're looking for, or xmlDoc.SelectNodes(patternString) to get a list of nodes we're looking for. The patternString parameter is precisely the request. It can be formed in one of two ways. Either as an XSL request or as an XPath request. A newer and preferred way to query an XML document is XPath. The patternString format must be set in advance, before the first call to either of the two data request methods, otherwise the XSL method of forming requests will be used by default. To set the formation type of patternString, use setProperty("SelectionLanguage", "format"). To change the queries in our example to use the XPath way, I'll add the following command: setProperty("SelectionLanguage","XPath"). In my opinion, XPath is the most important XML technology to learn. I'll give you some simple XPath queries. A good place to start learning this technology is the Microsoft XML SDK. Another way to explain this would be to write a simple Visual Basic application that allows you to enter queries and output the result. You may find some free apps that do the same thing, but XPath is fairly new and may not be fully supported by those apps.

2.3.1. Using XPATH to Query the Document Object Model

Let's add some code to the end of our previous example to return the contents of our order book:

GREAT! Let's now add another query that will allow us to determine whether the glass has a lid or not. Add the following code to the end of the previous one:

Set objNode = xmlDoc.selectSingleNode("/CUP/LID") if objNode.text="yes" then MsgBox "We have a lid" else MsgBox "No lid on this cup" end if

Let's go through the code line by line:

Line 1: Dim objNode As IXMLDOMNode

This line defines the objNode variable of type XML document node. It is important to understand that an XML document node is also an object. It doesn't matter. It consists of itself, as well as its attributes and children (childNodes). This way you can cut off unnecessary tree branches, selecting only the ones you need.

Line 2: Dim objListOfNodes As IXMLDOMNodeList

This line defines the objListOfNodes variable, which has the type of list of XML document nodes (group of nodes).

Line 3: xmlDoc.setProperty "SelectionLanguage", "XPath"

This line sets how the patternString is formed as an XPath.

Line 4: MsgBox "Your cup contains the following items:"

Line 5: Set objListOfNodes = xmlDoc.selectNodes("//CONTENTS/*[@qty>0]")

This line performs an XPath query that will return a group of nodes and store them in the objListOfNodes variable. The request is divided into the following parts:

  • //CONTENTS - take all CONTENTS elements in the XML document. Note: // is a shorthand for the entire content of the XML document.
  • /* - from the list of CONTENTS elements, take all (* - used to indicate all) descendant elements. This reduces the result to four element nodes ( ). These four nodes fall directly under the CONTENTS node.
  • [@qty>0] - check each child element to ensure that its qty attribute (@ - means attribute) is greater than 0. If this condition is not met, the node is discarded. Everything inside an XPath request can take the values ​​True or False. If the result is True, then the node is saved. If the result is False, then the node is discarded. After this, our result is reduced to three nodes (

Line 6-8: For Each objNode In objListOfNodes / MsgBox objNode.Text / Next

These rows display the values ​​of each element node that match the query. ("ice cube" , "straw" , "water").

Line 9: Set objNode = xmlDoc.selectSingleNode("/CUP/LID")

This line returns all LID elements that belong to the CUP element, which in turn is derived from the root of the tree (when the query begins with /, this means that you need to start from the root). This is very similar to the path to a file or folder. In our example, this query will return an LID element that contains the value "yes". The important thing here is that I told the request to start at the root element of the XML document. Queries do not always start at the root elements; they usually start at the current node. In our example, this does not matter, since the current node (xmlDoc) is the root element of the XML document (but this is not true in all cases).

Line 10-15: if objNode.text="yes" then / MsgBox "We have a lid" /
else / MsgBox "No lid on this cup" /end if

This line displays the message "We have a lid" because the element's LID text property is "yes".

3. Convert ADO to XML

Now that you understand the basics of XML, let's create an ActiveX control that will convert an ADO dataset into XML format. The goal is to get the book titles from the Titles table of the Pubs database and return them in XML format. I will use the result in my next article. You can say ADO has its own methods to save the result in XML format, right? Yes, but if I trust ADO to do this, I will end up with an XML file in such a terrible format that it will be impossible to work with. ADO will create the XML file using the namespace, and I don't need that at all right now. Secondly, ADO will create an XML file, which will be represented in the form of attributes. In other words, every record will become an element and every field an attribute:

But I would like to receive an XML file in the form of elements, where each entry would be contained in a tag , and each field would be an element inside the tag . My XML string syntax would be:

data from table data from table data from table data from table data from table datafrom table datafromtable

By the way, what I just did was create a schema for my XML string. Now, if I need to check the structure of an XML document against a schema, all I have to do is convert the schema into the correct format. That is, in DTD or XDR syntax. Notice that I have added some attributes to each element . One reason for this is that this information can be used by the client. Prettyname can be used as data labels. The datatype attribute could be used for client-side data validation. But to be fair, the real reason these attributes exist is because they have a special purpose in the XSL file template that I often use to build the where clause of SQL queries. Maybe I'll publish an article demonstrating this approach soon. The template is actually very useful. When the XML structure is applied to the data from the Titles table, the result will look like this:

The Busy Executive's Database Guide BU1032 The Busy Executive's Database Guide business 19.99 4095 An overview of available database systems with emphasis on common business applications. Illustrated. 6/12/1991 Cooking with Computers: Surreptitious Balance Sheets BU1111 Cooking with Computers: Surreptitious Balance Sheets business 11.95 3876 Helpful hints on how to use your electronic resources to the best advantage. 6/9/1991

Now I have something to work with!

Listing 1 - CUP.XML

glass 6 16 ice cube straw water yes

Dim xmlDoc As MSXML2.DOMDocument30 Set xmlDoc = New DOMDocument30 xmlDoc.async = False xmlDoc.validateOnParse = False xmlDoc.Load ("c:\inetpub\wwwroot\xml\cup.xml") MsgBox xmlDoc.xml Dim objNode As IXMLDOMNode Dim objListOfNodes As IXMLDOMNodeList xmlDoc.setProperty "SelectionLanguage", "XPath" MsgBox "Your cup contains the following items" Set objListOfNodes = xmlDoc.selectNodes("//CONTENTS/*[@qty>0]") For Each objNode In objListOfNodes MsgBox objNode. Text Next Set objNode = xmlDoc.selectSingleNode("/CUP/LID") If objNode.Text = "yes" Then MsgBox "We have a lid" Else MsgBox "No lid on this cup" End If

Listing 3 - ActiveX control: ADO in XML (WebClass.dll)(xmlControl.cls)

Option Explicit "Declare Database variables Private m_dbConnection As New ADODB.Connection Private m_dbCommand As ADODB.Command Private m_adoRs As ADODB.Recordset Private m_adoErrors As ADODB.Errors Private m_adoErr As Error Public nCommandTimeOut As Variant Public nConnectionTimeOut As Variant Public strConnect As Variant Public strAppName As String Public strLogPath As String Public strDatabase As String Public strUser As String Public strPassword As String Public strServer As String Public strVersion As String Public lMSADO As Boolean "Private Global Variables Private gnErrNum As Variant Private gstrErrDesc As Variant Private gstrErrSrc As Variant Private gstrDB As String Private gstrADOError As String Private Const adLeonNoRecordset As Integer = 129 Private gtableName(6) As String Private gcolumnName(6) As String Private gprettyName(6) As String Private gdatatype(6) As String Private gfilter(6) As String Private Function OpenDatabase() If Len(strConnect) = 0 Then "set default values ​​If Len(strDatabase) = 0 Then strDatabase = "pubs" End If If nConnectionTimeOut = 0 Then nConnectionTimeOut = 600 End If If nCommandTimeOut = 0 Then nCommandTimeOut = 600 End If If Len (strAppName) = 0 Then strAppName = "xmlControl" End If If Len(strUser) = 0 Then strUser = "sa" End If If Len(strPassword) = 0 Then strPassword = "" End If strConnect = "Provider=SQLOLEDB.1 ; " & _ "Application Name=" & strAppName & _ "; Data Source=" & strServer & "; Initial Catalog="&strDatabase&"; " & _ " User ID=" & strUser & "; Password=" & strPassword & ";" End If "connect to SQL Server and open the database On Error GoTo SQLErr "Enable the error handler With m_dbConnection .ConnectionTimeout = nConnectionTimeOut .CommandTimeout = nCommandTimeOut .Open strConnect "open the database using the connection string End With On Error GoTo 0 "turn off the error handler OpenDatabase = True "database opened successfully Exit Function SQLErr: Call logerror("OPEN") OpenDatabase = False End Function Private Function BuildSQLwhere(tmpWhere) As String "This is for the future End Function Public Function GetTitlesXML (Optional xmlWhere As Variant) As String Dim whereClause As String Dim strSQL As String Call OpenDatabase "open the pubs database If IsMissing(xmlWhere) Then "when the query fails whereClause = "" Else whereClause = BuildSQLwhere(xmlWhere)" convert the query to a correct one sql End If "initialize an sql expression that will query book titles strSQL = "select title_id,title,type,price,ytd_sales,notes,pubdate from titles " & whereClause Call NewRecordSet "create a data set "set cursorlocation m_adoRs. CursorLocation = adUseClient "open the recordset m_adoRs.Open strSQL, m_dbConnection, adOpenForwardOnly, adLockReadOnly, adCmdText "disconnect from the data set Set m_adoRs.ActiveConnection = Nothing On Error GoTo 0 "turn off the error handler "close the database and release the connection Call CloseDatabase If m_adoRs. EOF Then GetTitlesXML = "" "the query did not return any values ​​Else If lMSADO Then GetTitlesXML = msado(m_adoRs) "convert the ado recordset to custom xml End If End If "close the data set Call CloseRecordset Exit Function SQLErr: Call logerror(strSQL) End Function Private Function ADOtoXML(tmprs As ADODB.Recordset, tmpMP As Boolean) As String Dim adoFields As ADODB.Fields "declare a collection for storing fields Dim adoField As ADODB.Field "is used to get each field from the collection Dim xmlDoc As msxml2.DOMDocument30 Dim tmpLine As String "stores an xml representation of each book Dim tmpXML As String "is used to concatenate xml strings Dim i As Integer If tmprs.EOF Then "query did not return any records ADOtoXML = "" Exit Function Else Set adoFields = tmprs.Fields "create a collection of fields End If tmpXML = " " "all books will be enclosed in a tag Do Until tmprs.EOF "loop through each row in data set i = 0 " I is the index of the ado field, which starts at 0 - the first field will be field(0) tmpLine = " " & tmprs("title") & vbCrLf For Each adoField In adoFields "loop through all fields "build xml tag and its attributes for the current field tmpLine = tmpLine & " " & adoField.Value tmpLine = tmpLine & "" & vbCrLf i = i + 1 "move to the next field Next tmpXML = tmpXML & tmpLine & "" & vbCrLf "closing tag after the last field tmprs.MoveNext "next header Loop Set adoField = Nothing "destroy the field object Set adoFields = Nothing "destroy the field collection object tmpXML= tmpXML & ""&vbCrLf" closing tag Set xmlDoc = New msxml2.DOMDocument30 "create xmlDOM xmlDoc.async = False "wait for the document to load xmlDoc.validateOnParse = False "do not check the schema xmlDoc.loadXML(tmpXML) "load the string into the document object model On Error Resume Next "if the file does not exist, then we process this error Kill("c:\temp\custom.xml") "erase the file if it exists On Error GoTo 0 "tell the error handler to interrupt when an error is detected xmlDoc.save ("c:\temp\custom. xml") "save xml to file ADOtoXML=xmlDoc.xml "returns xml string Set xmlDoc=Nothing "destroy document object model End Function Private Function msado(tmprs As ADODB.Recordset) As String Dim xmlDoc As msxml2.DOMDocument30 On Error Resume Next "if the file does not exist, we get an error Kill ("c:\temp\msado.xml") "we erase the file if it exists On Error GoTo 0 "we tell the error handler to abort when an error is detected tmprs.save "c:\temp\msado .xml", adPersistXML "save the xml to a file Set xmlDoc = New msxml2.DOMDocument30 "create the xml document object model xmlDoc.async = False "wait for the xml document to load xmlDoc.validateOnParse = False "do not check the xmlDoc.Load schema ("C: \temp\msado.xml") "load the file into the document object model msado = xmlDoc.xml "return the xml string Set xmlDoc = Nothing "destroy the document object model End Function Private SubCloseRecordset() "close the data set m_adoRs.Close Set m_adoRs =Nothing End Sub Private Sub NewRecordSet() Set m_adoRs= Nothing Set m_adoRs=New ADODB.Recordset End Sub Private Sub CloseDatabase() m_dbConnection.Close Set m_dbConnection =Nothing End Sub Private Sub logerror(errSQL As String) Dim hFile As Integer Dim expFile As String On Error GoTo 0 gnErrNum = Err.Number gstrErrDesc =Err.Description gstrErrSrc = Err.Source Set m_adoErrors = m_dbConnection.Errors For Each m_adoErr In m_adoErrors gstrADOError = m_adoErr.Description & "," & CStr(m_adoErr.NativeError) _ & ", " & CStr(m_adoErr.Number) & "," & m_adoErr.Source _ & "," & CStr(m_adoErr.SQLState) Next hFile =FreeFile If Len(strLogPath) = 0 Then strLogPath = "C:\temp\" End If expFile = strLogPath & strAppName & ".err" Open expFile For Append As #hFile Print #hFile,"************************************* *******" Print #hFile, Now() Print#hFile, "************************************** ****" Print #hFile,"Subroutine: " & tmpPro Print #hFile, "Error Number:" & gnErrNum Print#hFile, "Error Description: " & gstrErrDesc Print #hFile, "Error Source:" & gstrErrSrc Print # hFile, "Ado error String: " & gstrADOError Print #hFile, "Bad SQL: " & errSQL Close #hFile End Sub Private Sub Class_Initialize() strVersion = "xmlControl Version 1. 1" "title_id,title,type,price,ytd_sales,notes,pubdate gtableName(0) = "titles" gcolumnName(0) = "title_id" gprettyName(0) = "Title Identification Number" gdatatype(0) = "number" gfilter(0) = "" gtableName(1) = "titles" gcolumnName(1) = "title" gprettyName(1) = "Title of the Book" gdatatype(1) = "text" gfilter(1) = "" gtableName (2) = "titles" gcolumnName(2) = "type" gprettyName(2) = "Type of Book" gdatatype(2) = "text" gfilter(2) = "" gtableName(3) = "titles" gcolumnName( 3) = "price" gprettyName(3) = "Price of the Book" gdatatype(3) = "number" gfilter(3) = "" gtableName(4) = "titles" gcolumnName(4) = "ytd_sales" gprettyName( 4) = "Year to date sales" gdatatype(4) = "number" gfilter(4) = "" gtableName(5) = "titles" gcolumnName(5) = "notes" gprettyName(5) = "Notes about the book " gdatatype(5) = "memo" gfilter(5) = "" gtableName(6) = "titles" gcolumnName(6) = "pubdate" gprettyName(6) = "Date Published" gdatatype(6) = "date" gfilter (6) = "" End Sub

Listing 4 - VB test application to test WebClass

Private Sub Command1_Click() Dim objWC As xmlControl Dim xml As String Set objWC = New xmlControl objWC.strDatabase = "pubs" objWC.strServer = "ltweb" objWC.strUser = "sa" objWC.strPassword = "" objWC.lMSADO = Option2 .Value objWC.strAppName = "Article1" Text1.Text = objWC.getTitlesXML End Sub

Listing 5 - ASP for testing WebClass

The XML format is designed to store data that may be useful in the operation of certain programs, websites and support for certain markup languages. It is not difficult to create and open a file with this format. This can be done even if you do not have any specialized software installed on your computer.

XML itself is a markup language, somewhat similar to HTML, that is used on web pages. But if the latter is used only for displaying information and its correct markup, then XML allows it to be structured in a certain way, which makes this language somewhat similar to an analogue of a database that does not require a DBMS.

You can create XML files using specialized programs or the text editor built into Windows. The ease of writing code and the level of its functionality depend on the type of software used.

Method 1: Visual Studio

Instead of this Microsoft code editor, you can use any of its analogues from other developers. In fact, Visual Studio is a more advanced version of the usual "Notepad". The code now has special highlighting, errors are highlighted or corrected automatically, and special templates are already loaded into the program that make it easier to create large XML files.

To get started you need to create a file. Click on an item "File" in the top panel and from the drop-down menu select "Create…". A list will open indicating the item "File".

  • You will be redirected to a window with a choice of file extension, select the item accordingly "XML file".
  • The newly created file will already have the first line with the encoding and version. By default, the first version and encoding are specified UTF-8, which you can change at any time. Next, to create a full-fledged XML file, you need to write down everything that was in the previous instructions.

    When finished, select again in the top panel "File", and there is an item from the drop-down menu "Save everything".

    Method 2: Microsoft Excel

    You can create an XML file without writing code, for example, using modern versions of Microsoft Excel, which allows you to save tables with this extension. However, you need to understand that in this case it will not be possible to create something more functional than a regular table.

    This method is more suitable for those who do not want or do not know how to work with code. However, in this case, the user may encounter certain problems when rewriting the file in XML format. Unfortunately, the operation of converting a regular table to XML is possible only on the newest versions of MS Excel. To do this, use the following step-by-step instructions:


    Method 3: Notepad

    Even a regular one is quite suitable for working with XML "Notebook", however, it will be difficult for a user who is not familiar with the syntax of the language, since various commands and tags need to be written in it. The process will be somewhat simpler and much more productive in specialized programs for editing code, for example, in Microsoft Visual Studio. They have special tag highlighting and tooltips, which greatly simplifies the work of a person new to the syntax of this language.

    This method does not require downloading anything, since it is already built into the operating system. "Notebook". Let's try to make a simple XML table in it using these instructions:


    Your finished result should look something like this:




    25
    True


    XML compilers must process this code as a table with one column containing data about a certain Ivan Ivanov.

    IN "Notepad" it is quite possible to make simple tables like this, but when creating larger data sets, difficulties may arise, since in ordinary "Notepad" There are no functions for correcting errors in the code or highlighting them.

    As you can see, there is nothing complicated in creating an XML file. If desired, it can be created by any user who more or less knows how to work on a computer. However, to create a full-fledged XML file, it is recommended to study this markup language, at least at a primitive level.

    In the previous article about XML, we looked at such an outdated method of validating XML documents as the XML DTD. This method is still used to validate XML data, but every day it is increasingly being replaced by a new technology called XML Schema. Many shortcomings that were in the XML DTD have been corrected in XML schemas, so at the moment all leading developers use only XML schemas for document validation.

    To appreciate the advantages of XML Schemas over DTDs, let's take a closer look at the main disadvantages of DTDs that have been successfully corrected in XML Schemas. I already mentioned them in the article “”, but for a better understanding, let’s repeat.

    Disadvantages of XML DTD over XML Schema

    1. Language syntax different from XML. That is, DTD is not XML. In this regard, various problems may arise with the encoding and verification of XML documents.
    2. No data type checking. There is only one data type in an XML DTD—string. In this regard, for example, if there is text in a numeric field, the document will still pass verification, since the XML DTD cannot check the data type.
    3. You cannot assign more than one DTD description to one XML document. That is, a document can be verified with only one DTD description. If there are several of them, you will have to redo the descriptions and combine everything in one file, which is very inconvenient.

    These were the main shortcomings of the XML DTD, which were successfully corrected in the industry standard for describing XML documents, XML Schema.

    XML Schema is an industry standard for describing XML documents

    In short, XML Schema does the following:

    1. Describes the names of elements and attributes (dictionary).
    2. Describes the relationship between elements and attributes, as well as their structure (content model).
    3. Describes data types.

    I also want to note that at the moment almost everything can be described using diagrams. That is, a schema is a universal way of describing the grammar of data, which can be used not only for verifying XML documents, but also for describing databases, etc. Thus, the scope of application of the schemes is currently very wide.

    Example XML Schema for validating an XML document

    As practice shows, the material is absorbed much better if you immediately start studying with examples. I’ll say right away that we won’t go into all the details, since the material is very complex, especially if you study it in text form.

    Example of a simple XML schema

    Using this schema, you can validate the following XML document.

    <книга xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation = "book.xsd"> <название>XML Basics <цена>300

    So let's go back to our XML schema. As you have already noticed, XML, already known to us, is used to create XML schemas. The only difference here is that XML Schema has elements already defined, unlike regular XML. In this regard, namespaces are used. In this case, the required namespace will be “http://www.w3.org/2001/XMLSchema”, which will be specified using the “xs” prefixes.

    I would like to note right away that you can use both namespace prefixes and set a namespace for the root element. There is no difference as such. Everyone decides for themselves what to do in a given situation. Let me just say that the prefixes “xs” or “xsd” are usually used.

    Well, now let's figure out how to decipher the above diagram. As mentioned above, XML Schema is a description of a vocabulary and data types. Based on this, we will decipher each element.

    • — declare the “book” element with the “Book” type.
    • — declare a complex type with the name “Book” (xs: complexType - can contain nested elements).
    • — declaration of nesting. That is, the type will contain nested elements.
    • — declare an element with the name “title” (standard type “string” - xs:string).
    • — declare an element with the name “price” (standard type “number” - xs:decimal).

    As you can see, there is nothing super complicated here. If you think about it, everything is very simple.

    Basic XML Schema Elements

    To be brief, the XML schema can be described as follows.

    Your scheme

    As you can see from the example, each XML schema consists of a root element “schema” and a required namespace “http://www.w3.org/2001/XMLSchema”. Next comes a description of the circuit and the circuit itself. At the same time, very often in very high-quality schemas the description is much larger than the XML Schema itself.

    Description of elements in XML Schema

    At the beginning of the article, we already looked at an example of a simple XML schema. In it we separately described elements and types. At the same time, I would like to immediately note that the sequence does not play a role here. The scheme will work in any case.

    Now let's look at the second way of writing XML Schema, which is based on describing the type immediately inside the element. This method is suitable if you do not plan to use the same description for different elements. For clarity, let's look at an example.

    As can be seen from the example, an element is declared using a special construction “element” using the appropriate prefix. In this case, we define an element called “root” without specifying a type, since it will be described inside the element. That is, there are two ways to describe elements.

    1 way

    Type Description

    Method 2

    Description of element type

    You can use both the first method and the second. They all work the same way. The only question is convenience in this particular case.

    Further, after declaring the element, we indicate that it is of complex type ( ) and list ( ) nested elements. In this case, these are the name and age elements with types “xs:string” and “xs:integer”. The xs prefix means that it is a base type that is already defined in the XML Schema standard.

    As you can see, everything is quite simple so far. Again, we will not go into all the details, since this article is intended to familiarize you with XML Schema, and not to study it in detail.

    How XML Schema and document are matched

    The peculiarity of XML Schema is that it describes not the document itself, but the namespace. In this regard, most often there is no mention of it in the document. The handler itself maps the schema you need without using any instructions in the XML document.

    In case the handler does not know where the schema is, we can indicate where to look for it. This is done using the special attribute “schemaLocation”. Since this attribute belongs to a different namespace, the namespace must also be specified before using the attribute. For clarity, let's look at an example.

    XML Schema

    XML document

    Now let's look at each line in detail.

    • targetNamespace=”http://www.site.com” – indicate which namespace this XML Schema is for.
    • xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” – we connect the namespace in which the “schemaLocation” attribute is described.
    • xsi:schemaLocation=”http://www.site.com/product.xsd” – we indicate where the schema can be found in case the parser does not know where it is. If the XML document does not belong to any namespace, and therefore there is no reference to it in the schema, then the “schemaLocation” attribute is replaced with “noNamespaceSchemaLocation” (a reference to the schema without defining namespaces).

    That's all. Good luck and success in learning XML!