VC Operation XML Programming instance

Source: Internet
Author: User
Tags add define object exit exception handling functions object model string
Xml| programming

XML Programming Instance

Article body

Some time ago, due to the needs of the work, the use of XML, so it has been a number of simple research. Here would like to write out some of the experience, and share with you, the wrong place also hope to forgive.

1. What is XML?
First of all, I think you should all probably know what XML is. If you don't have a concept of what XML is, you can look at some of the relevant material and I won't say more.

2. Why use XML?
In fact, at the beginning I was not very clear, and later in the work only slowly realized. First of all, I write the program needs to send a lot of data structure, such as tables, trees and so on. To be in the past, I would like to define a data structure myself. It's a pretty messy thing to do, and when the structure needs to be constantly updated and flexible, it's even more frustrating, not to mention versatility and cross-platform. At this point, the strong ability of XML to express the tree-structured data is displayed. such as a tabular data.

11
12

21st
22


<TABLE>
<TR>
<TD> 11</td>
<TD>12</TD>
</TR>
<TR>
<TD> 21</td>
<TD>22</TD>
</TR>
</TABLE>


The above description, very simple and clear, universal and cross-platform is very obvious. Of course, the price is also there, that is, the data used to express information become larger. This requires you to weigh in between performance and scalability again, XML is now in vogue, and its predecessor (say like more appropriate) HTML is a testament, not to mention Microsoft. NET plan is the architecture above XML.

Finally, because of the popularity of XML, there are more and more development tools (SDK), for example, XML parser have many kinds. With these tools, we can develop faster, reducing unnecessary hassles----such as defining a set of specifications, developing relevant operational tools, and so on, and not being able to communicate with the outside world.

3. What development tools to use

Here, we are facing the programmer, still refers to VC + + programmer. We have a lot of choices, but it should be nice to choose Microsoft's XML Parser SDK, at least in a very detailed document (at this point, Microsoft has been doing a good job). Of course there are many other options, such as Excel on the apache.org. For more detailed information, please see www.ibm.com/xml.

Basic concepts

Programming patterns FOR XML

As we said before, XML is very powerful for tree expression, we can express an XML document with a tree, the operation of the document is the operation of the tree, this is the DOM (Document Object model). However, Dom has many problems with the processing of XML documents, such as slow speed, and then there is another model of sax.

Below, we describe each of these two models in detail.

DOM Model

The DOM model needs to scan the entire XML document and then parse to generate an object tree, all tags and attributes in the XML document are represented by objects rather than an isolated text. Because it is an object, there is a context that contains a relationship.

That's basically it.

Doc

Element

Note

Text

Doc refers to the entire tree object, including the basic properties.

An element is a label that can contain a node object for attributes and child nodes (Chilnode).

Note is also a label, but it cannot contain child nodes and attributes.

Text is a simple literal.

Since it is a tree operation, it is necessary to include the nodes of the addition, deletion and browsing, and other basic functions. With these features, you can completely manipulate the XML document. Object-level operations are much easier and more intuitive than direct manipulation of text.

Sax model

We said that the disadvantage of the DOM model is that it is slow and wastes memory. Because in many cases, we do not need to scan the entire XML document. There is no need to generate a large tree structure, especially when the file is large, if only some of the information is needed.

The SAX model is to scan XML documents while processing them. Like many program design ideas, Sax is event-driven. This means that it can generate different messages in the process of processing, and call the corresponding functions for processing. And it's important to quit at the halfway point. For example, the Web page in the process of downloading, you can download, while the next part of the analytic display.

According to the different situations, we use different methods to deal with.

It should be explained that these models of XML are defined by the standardized organization, not by a company's specifications. Therefore, the transplant of the program should be more convenient.

Examples of XML programming

Because the Microft XML Parser document is more comprehensive, and the combination of Visual C + + is very close, we are here to use such a combination for example, for other languages, you can extrapolate.

A note on the Microsoft XML parser:

All objects are COM objects. To this end, we use Smartpointer to reduce the addref,releaseref trouble. Similarly, because the use of string unity is BSTR type, the release of memory is also a more troublesome thing, so the _bstr_t class to encapsulate the BSTR data type, can reduce unnecessary trouble.

DOM Model:

As already mentioned, for the DOM model, the entire XML file is parsed into a tree-shaped structure. All tags, attributes, etc. are treated as objects. Therefore, we must understand the meaning of the object, and its relationship with each other in order to correctly operate.

In order to have a perceptual knowledge first, let's begin. (for the convenience of illustration, there is basically no exception handling in the code)

Generate an XML literal

Let's say we're going to create an XML literal like the following


-11

9


We should first create a Document object, as follows: Msxml::ixmldomdocumentptr PDoc;

Pdoc.createinstance (__uuidof (MSXML::D omdocument));

If the creation succeeds, then we get a XMLDOMDocument object instance. The next step is to add the root node documentelement, remembering that XML has only one root.

Create an Element object as the root node

Msxml::ixmldomelementptr pdocelement=pdoc->createelement ("the");

Insert the root node into the directory tree

Pdoc->appendchild (pdocelement);

All right, let's take a look at the result: with Pdoc-> XML, you can get the text of the entire DOM object because there's nothing under the tree root, so just show now, we're going to insert the child node under the root, and set the node text (text)

Msxml::ixmldomelementptr pnewchildelement;
Pnewchildelement=pdoc->createelement ("Beijing");
Pnewchildelement->puttext ("-11");
Pdocelement->appendchild (pnewchildelement);
At this point the entire XML literal should be


-11


Then add a child node and set the node attributes (attribute) pnewchildelement=pdoc->createelement ("Shanghai");
Pnewchildelement->puttext ("9");
Pnewchildelement->setattribute ("Weather", _variant_t ("cloudy")); Pdocelement->appendchild (pnewchildelement);

So we can get the expected XML text.
Other actions:
Delete action:
To delete a child node from the parent node Pdocelement->removechild (pnewchildelement)
Disk Operation:
Pdoc->save ();
Load an existing XML literal
If we already have an XML file that we want to parse, we can load it with the Document object's load or Loadxml and parse it while we load it.

If the load succeeds, a tree structure is generated in memory. With the DOM model, we can do all sorts of things. The most common is that we need to look for specific information and deal with it.

Find positioning

Use selectSingleNode (XPath), selectnodes (XPath) to locate the tag and get the corresponding node (s) object.

Xpath

XPath is a string similar to a file path name, and is also a SQL query that limits the lookup scope.

Find the specified object, we can all kinds of processing, add, delete, value, and so on.

Summary: The above is simply a simple introduction to the programming of the DOM model, with a view to getting started quickly. For more information, you must also consult the SDK documentation. If possible, the SAX model, XSLT conversion to XML, and so on will be introduced later.

RELATED links: To use MSXML Parser, you must first download its SDK and runtime.

Http://download.microsoft.com/download/xml/Install/3.0/WIN98Me/EN-US/msxml3.exe

Http://download.microsoft.com/download/xml/SDK/3.0/WIN98Me/EN-US/xmlsdk.exe

-------------The following is a code instance-----------

#include "stdafx.h"

#include "iostream.h"

#include "msxml.h"

#include "atlbase.h"

#import "Msxml.dll"//Introduction type library

#ifdef _DEBUG

#define NEW Debug_new

#undef This_file

static char this_file[] = __file__;

#endif

int Exit ();

void Loadfromstring ();

void Createxml ();

XML text Template

_bstr_t xmltemple= "-11 9";

int main ()

{

cout << "XML Programming-Demonstration program" << Endl;

CoInitialize (NULL); Initializing a COM environment

cout << "------Generate new XML text------" << Endl;

Createxml ();

cout << "------Read existing XML text------" << Endl;

Loadfromstring ();

return Exit ();

}

void Createxml ()

{

Msxml::ixmldomdocumentptr PDoc;

HRESULT hr =pdoc.createinstance (__uuidof (MSXML::D omdocument));

if (! SUCCEEDED (HR))

{

cout << "Cannot create DOMDocument object, please check if Ms XML Parser runtime is installed!" << Endl;

Exit ();

}

Msxml::ixmldomelementptr pdocelement=pdoc->createelement ("the");

Pdoc->appendchild (pdocelement);

cout << "Generate root: \ n" << pdoc->xml << Endl;

Msxml::ixmldomelementptr pnewchildelement;

Pnewchildelement=pdoc->createelement ("Beijing");

Pnewchildelement->puttext ("-11");

Pdocelement->appendchild (pnewchildelement);

cout << "Add node: \ n" << pdoc->xml << Endl;

Pnewchildelement=pdoc->createelement ("Shanghai");

Pnewchildelement->puttext ("9");

Pnewchildelement->setattribute ("Weather", _variant_t ("cloudy"));

Pdocelement->appendchild (pnewchildelement);

cout << "Add nodes again: \ n" << pdoc->xml << Endl;

Pdocelement->removechild (pnewchildelement);

cout << "Delete the newly added node: \ n" << pdoc->xml << Endl;

}

void Loadfromstring ()

{

Msxml::ixmldomdocumentptr PDoc;

HRESULT hr =pdoc.createinstance (__uuidof (MSXML::D omdocument));

if (! SUCCEEDED (HR))

{

cout << "Cannot create DOMDocument object, please check if Ms XML Parser runtime is installed!" << Endl;

Exit ();

}

Pdoc->loadxml (xmltemple);

cout << "Read results: \ n" << pdoc->xml << Endl;

Msxml::ixmldomelementptr pdocelement=pdoc->getdocumentelement ();

Msxml::ixmldomelementptr Pelement=pdocelement->selectsinglenode ("Shanghai");

Pdocelement->removechild (pelement);

cout << "Locate delete Shanghai node: \ n" << pdoc->xml << Endl;

cout << Save Results ... (Analog only) "<< Endl;

cout << "OK, that's simple" << Endl;

}

int Exit ()

{

GetChar ();

return 1;

}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.