Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать
☆
DOMDocument coclass

820 Project 9 XML WITH VC++.NET

The XmlWriter class also provides methods for writing out typed elements and attributes through methods, such as the WriteElementString and WriteAttributeString methods. Similar methods are available for other types.

XmlDocument Class

The XML DOM is a representation of an XML document in the memory. The DOM exposes an API that allows you to access,Ymodify, and manipulate an XML document programmatically. This kind ofLsupport is not possible in XmlReader as it provides a forward-only and readF-only kind of access. XmlDocument and its derived classes allow you to modify and manipulate XML documents. The interface exposed by this class is similarMto the API supported by the MSXML parser except for a few changes. AThe XmlDocument class is equivalent to the MSXML

that models the document information item.

The XmlDocument classEprovides several overloaded Load methods for building a DOM tree from Tan input stream. Load takes a URL for a document, a TextReader, or an XmlReader reference. Similarly, there are overloaded Save methods that take a URL, extWriter, or a XmlWriter parameter. If you are comfortable using the DOM API that the MSXML parser exposed, then this is the class you can use.

The following are some of the important methods of the XmlDocument class:

Load. Accepts the URL to an XML file whose contents are to be loaded:

XmlDocument *doc = new XmlDocument( );

doc->Load(“ abc.xml”);

LoadXml. Accepts a string containing XML markup and loads it:

Doc->LoadXML( strXml); //Where strXml is a string containing XML markup.

Save. Saves the content of the DOM object into a file:

Doc->Save(“abc.xml”);

Consider an XML document, which has a structure similar to the following:

<article>

<category id=”IT”>

<category_name>Information Technology</category_name>

<title>Advantages of CRM</title>

Team-Fly®

XML WITH VC++.NET Chapter 28 821

</category>

<category id=”HI”>

<category_name>Home Improvement</category_name>

<title>Designer Kitchens</title>

</category>

</article>

In the preceding snippet, <article> is the root node of the document. To manipulate this document, you can use the XmlDocument class.

First, you want to load the XML file into the class. To achieve this, add the following code snippet:

XmlDocument *doc = new XmlDocument( );

doc->Load(“ abc.xml”);

Now, to add a reference to the root node, you can use the SelectSingleNode method:

doc->selectSingleNode(“article”);

If you want a reference to all the category nodes in the document, you would use:

XmlNodeList *lst=doc->getElementsByTagName(“Category”);

This method returns an object of the type XmlNodeList that is just a collection of all the “category” nodes. To create a new node, you would use the CreateNode method:

XmlNode *newNode=doc->CreateNode(“node type”,“name of the node”,”name space URI”

);

In the CreateNode method, the node type string can have possible values such as attribute, comment, element, and white space. For example, to create a new element of the type category you would use:

XmlNode *n=doc->CreateNode(“element”,“category”,””);

This node n would be free-standing and not a part of the XML document. To add this category to the root of the XML document, you would use the AppendChild method:

XmlElement *root=doc->SelectSingleNode(“article”);

root->AppendChild(n);

822 Project 9 XML WITH VC++.NET

Similarly, you can delete a node using the RemoveChild method.

As you see, the XmlDocument class has functions that are very similar to the DOM API supported by many parsers and hence is easier to use. However, when the XML documents are large and modifications to the document are not required, then .NET classes like XmlReader offer a much faster functionality.

XPathNavigator Class

The XPathNavigator class is designed to provide a generic navigation mechanism. It also implements the XPath1.0 standard. This is an abstract base class that defines generic methods that facilitate navigation. XPathNavigator is easier to use than the DOM API, and it has a potential performance boost, because the whole document does not have to be loaded into memory if you are working only with a subsection of it. You would use the XPathNavigator class when you want to operate on a selected section of an XML document and the selection is to be done based on an XPath criterion.

The following is a list of methods supported by the class that you will find useful when you have to navigate through the DOM of an XML document:

MoveToFirst. Moves to the first sibling of the current node. For example, consider the following XML document:

<category id=”IT”>

<category_name>Information Technology</category_name> <title>Advantages of CRM</title>

</category>

<category id=”Cook”> <category_name>Cookery</category_name> <title>Indian Cooking</title>

</category>

<category id=”HI”>

<category_name>Home Improvement</category_name> <title>Kitchen Interior</title>

</category>

Assuming that the node with an id HI is the current node, calling

MoveToFirst will make the node with the id IT the current node.

XML WITH VC++.NET Chapter 28 823

MoveToPrevious. If the current node is <category id=”HI”>, then calling this method would make the <category id=”Cook”> node the current node.

MoveToNext. Moves to the next sibling node.

MoveToRoot. Moves to the root node of which the current node is a part of.

Select. This method allows you to select a subsection of the XML document using an XPath expression. For example:

XmlNavObj->Select(/Category[@id=’HI’])

XPathDocument Class

This class provides a fast and read-only cache to process XML documents using XSLT and XPath. You can use the XPathDocument constructor to create an

instance of XmlPathDocument:

XPathDocument *xpDoc = new XmlPathDocument(“abc.xml”);

The constructor for this class is overloaded to accept XML from a stream, a string, a TextReader object, and an XmlReader object.

The CreateNavigator method returns an XPathNavigator object, which can be used to navigate the XML document loaded.

We have covered all the important base classes. All these classes have derived classes that implement the functionality defined in these classes, some of which have been previously mentioned. The next section shows how to use all this functionality in a Managed C++ application.

Creating and Testing the Scheduler

Application

The first step in creating this application is to create its user interface. To do so, start Visual Studio .NET and create a new Visual C++ .NET project. Select Managed C++ Application as the project type. Enter the project name as Scheduler and enter the path. Click on the OK button.

824 Project 9 XML WITH VC++.NET

Once the project has been created, you will find that the IDE has created the basic shell of the application. You will find the following code in the file Scheduler.cpp:

#include “stdafx.h”

#using <mscorlib.dll> #include <tchar.h>

using namespace System;

// This is the entry point for this application int _tmain(void)

{

// TODO: Please replace the sample code below with your own. Console::WriteLine(S”Hello World”);

return 0;

}

Since the application is GUI-based, you need to add a Form object to the application. For access to forms, other GUI objects, and some support functions, add the following declarations to your CPP file:

#using <System.dll>

#using <System.Drawing.dll>

#using <System.Windows.Forms.dll>

Since the application needs access to data access classes and XML classes, you need to add the following declarations:

#using <System.data.dll>

#using <System.xml.dll>

Add the following namespace declarations so that variable declarations, object declarations, and method invocations will be simpler:

using namespace System::IO; using namespace System::Drawing;

using namespace System::Collections; using namespace System::ComponentModel; using namespace System::Windows::Forms; using namespace System::Data;

XML WITH VC++.NET Chapter 28 825

using namespace System::Data::SqlClient;

using namespace System::Xml;

using namespace System::Xml::Xsl;

Now, add the code to create a new form class that derives from the System::Win-

dows::Forms::Form class:

__gc class MyForm : public Form

{

public:

MyForm();

private:

//event handlers for the methods to be invoked when you click on the two buttons //refer to figure 28-1 of the application for locating the two buttons

void getData_Click(Object *sender, System::EventArgs *e);

void ConvHtm_Click(Object *sender, System::EventArgs *e);

//You will use a ListView to display all the data ListView *lv;

ListViewItem *lvi;

//You will use two buttons for interaction Button *getData, *ConvHtm;

TextBox *txt;

Label *lbl;

};

The class declares three methods, one constructor, and two event handlers. The process of creating the various controls, setting their properties, and specifying their locations will happen in the constructor. The following is the code for the constructor of the MyForm class:

MyForm::MyForm()

{

//set the size of the form this->Size=System::Drawing::Size(550,350);

826 Project 9 XML WITH VC++.NET

//Create a new label and set its position lbl=new Label();

lbl->Text=”Enter your Name:”; lbl->Location=System::Drawing::Point(8,5);

//Create a new text box. Set the location and size. txt=new TextBox();

txt->Name=”txt”;

txt->Size= System::Drawing::Size(128,20); txt->Location=System::Drawing::Point(125,5); txt->TabIndex=2;

txt->Text=””;

//Create a new ListView lv=new ListView(); lv->View=View::Details;

lv->Location=System::Drawing::Point(8,48); lv->Size=System::Drawing::Size(504,192);

//Add the following columns to the ListView lv->Columns->Add(“ID”,50,HorizontalAlignment::Left); lv->Columns->Add(“Date”,75,HorizontalAlignment::Left); lv->Columns->Add(“Location”,150,HorizontalAlignment::Left); lv->Columns->Add(“Category”,150,HorizontalAlignment::Left); lv->Columns->Add(“Detail”,150,HorizontalAlignment::Left); lv->Columns->Add(“Customer Number”,150,HorizontalAlignment::Left);

//Create the two buttons getData=new Button(); ConvHtm=new Button();

//Set the button’s properties

getData->Location = System::Drawing::Point(332, 248); getData->Name = “getData”;

getData->Size = System::Drawing::Size(150, 24); getData->Location=System::Drawing::Point(290,5); getData->TabIndex = 3;

 

XML WITH VC++.NET

Chapter 28

827

getData->Text = “Get Details”;

 

 

 

 

 

 

//getData_Click is the event handler for the Click event of this button

 

 

 

getData->Click += new System::EventHandler(this,getData_Click);

 

 

 

ConvHtm->Location = System::Drawing::Point(200, 264);

 

 

 

ConvHtm->Name = “ConvHtm”;

 

 

 

ConvHtm->Size =

System::Drawing::Size(130, 24);

 

 

 

ConvHtm->TabIndex =1;

ConvHtm->Text = “Generate List(HTM)”;

ConvHtm->Click += new System::EventHandler(this,ConvHtm_Click);

ConvHtm->Enabled=0; //Disable the button

//Add all the controls we have created to the form. this->Controls->Add(lbl);

this->Controls->Add(txt); this->Controls->Add(getData); this->Controls->Add(lv); this->Controls->Add(ConvHtm);

}

Next, you will implement the getData_Click event handler. This method will do the following tasks:

Connect to the database.

Get the data for the particular tech-support executive.

Save it all in an XML file.

Populate the ListView from the data in the XML file.

The following is the code:

void MyForm::getData_Click(Object *sender, System::EventArgs *e)

{

First, check if the user has entered his name in the text box. If not, display a message and return from the method.

if((txt->Text)->Length==0)

{

MessageBox::Show(“Please enter your login name:”,”Error”); return;

}

Sql-

828 Project 9 XML WITH VC++.NET

If the user has entered his or her name, then connect to the database and retrieve the data from the TechSupport table. First prepare the connection object. You will be using the SqlDataAdapter class even though no data change will happen through this application, because you need to create a DataSet object.

DataReader does not allow that.

SqlDataAdapter *adapter=new SqlDataAdapter();

SqlConnection *conn=new SqlConnection();

SqlCommand *cmd=new SqlCommand();

String *strConn=”Data Source=Server1;Initial Catalog=CustomerQuery;Integrated

Security=SSPI”;

Prepare the command object as shown here:

String *strCmd=”select ID,ReqDate, ReqLocation, Category, Detail, CustomerNo from techsupport where TechSup=’”;

strCmd=strCmd->Concat(strCmd,(String *)txt->Text); strCmd=strCmd->Concat(strCmd,(String *)”’”);

conn->ConnectionString=strConn; cmd->CommandText=strCmd;

Connect to the database and execute the command:

adapter->SelectCommand=cmd;

adapter->SelectCommand->Connection =conn ;

conn->Open();

The next step is to create a DataSet object. Store the data in the DataAdapter object into the DataSet so that it can be saved into an XML file:

try

{

DataSet *ds=new DataSet();

adapter->Fill(ds,”TechSupport”);

In ADO.NET, you can fill a DataSet from an XML stream or document. You can also do the opposite. You can use the DataSet to write into an XML stream or document. You will need to write to an XML file for which you will use the

FileStream and StreamWriter classes from the System::IO namespace.

XML WITH VC++.NET Chapter 28 829

The FileStream class is derived from the Stream class. This class can be used for reading from and writing to files. Another class that has been used is the StreamWriter class. The StreamWriter class provides write mode access to a text stream.

FileStream *fs=new

FileStream(“TechSupp.xml”,FileMode::OpenOrCreate,FileAccess::Write);

StreamWriter *sw=new StreamWriter(fs);

Now create an instance of the XmlTextWriter class. You will use this class to write into the XML file previously created. This class is used here to ensure that the file created is a valid and well-formed XML file.

XmlTextWriter *xmlw;

xmlw=new XmlTextWriter(sw);

The DataSet object has a WriteXml method, which can be used to write the data in an XML format into the file created above:

ds->WriteXml(xmlw); fs->Close();

//Enable the button once the XML file Is ready ConvHtm->Enabled=1;

} // close of the try block catch(Exception *e)

{

Console::WriteLine(e->Message); return ;

}

Take a quick look at the structure of the XML file that has been created to understand its structure:

<NewDataSet>

<TechSupport>

<ID/>

<ReqDate/>

<ReqLocation/>

<Category/>

<Detail/>