Add an event handler for the dialog box's Save button. In a real-world application, you would include much more error handling and data validation. However, this example focuses on the XML.
After calling UpdateData, the function builds the file name using the video title and format. An XMLTextWriter object then is instantiated and several of its methods are used to perform such tasks as starting the document and writing elements and attributes. Note how in some cases the WriteElementString is used and in other situations where more information is neededsuch as when writing nested elements or elements with attributesthe WriteStartElement is first called, the addition information is written, and then the WriteEndElement function is called to terminate that element:
void CVideoInfoDlg::OnBnClickedSave()
{
#pragma push_macro("new")
#undef newif (UpdateData())
{
XmlTextWriter* xmlwriter;
try
{
String* fileName = String::Format(S"{0}-{1}.xml",
(String*)m_strTitle,
(String*)m_strFormat);
fileName = Path::Combine(m_strWorkingDir,
fileName);
xmlwriter = new XmlTextWriter(fileName,
Text::Encoding::ASCII);
xmlwriter->WriteStartDocument(true);
xmlwriter->WriteStartElement(S"VideoInfo");
xmlwriter->WriteAttributeString(S"Format", m_strFormat);
xmlwriter->WriteElementString(S"Title", m_strTitle);
xmlwriter->WriteElementString(S"Director", m_strDirector);
xmlwriter->WriteStartElement(S"Actors");
for (int i = 0; i < m_lbxActors.GetCount(); i++)
{
CString strActor;
m_lbxActors.GetText(i, strActor);
xmlwriter->WriteElementString(S"Actor", strActor);
}
xmlwriter->WriteEndElement(); // end of Actors
xmlwriter->WriteElementString(S"Studio", m_strStudio);
xmlwriter->WriteElementString(S"ReleaseYear",
m_iReleaseYear.ToString());
xmlwriter->WriteElementString(S"Runtime",
m_iRuntime.ToString());
xmlwriter->WriteEndElement(); // end of VideoInfo
xmlwriter->WriteEndDocument();
MessageBox::Show(S"Video information successfully saved");
}
catch(Exception* e)
{
MessageBox::Show(e->Message);
}
__finally
{
xmlwriter->Flush();
xmlwriter->Close();
}
}
#pragma pop_macro("new")
}
Now, you add the function to open an existing video-information file. Add an event handler for the Open button and code it as follows.
(continued)
The function begins by displaying a dialog box for the user to specify a file to open. An XMLTextReader object is instantiated to read that file's nodes. A basic while loop is used, where the XMLTextReader::Read method is called until it returns false (indicating end of file).
Within the loop, the XmlTextReader::NodeType property is inspected to ensure that only elements nodes (XmlNodeType::Element) are processed. If the node type is an element, the function then determines whether the current element is one whose value needs to be retrieved for display on the dialog box. If it is, the value is retrieved using the XmlTextReader::ReadString method. Because the Format value is stored as an attribute of the VideoInfo element, the XmlTextReader::GetAttribute method is used to obtain that value if the current element's Name value is equal to "VideoInfo":
Finally, build and test the application. You should have a fully functional application that uses the .NET XML classes to store and retrieve data. Figure 2 shows an example of running this application with information from the famous Reservoir Dogs movie displayed.
Figure 2: Example Running of the Demo Application
Figure 3 shows the same video file's information as displayed in Internet Explorer.
Figure 3: You Can Open the File Using Any XML Parser (including Internet Explorer)
Looking Ahead
As previously mentioned, the XmlTextWriter/XmlTextReader classes are used in situations where your application's design allows for the writing or reading of an XML file's nodes in sequential order. Although this works fine for certain scenarios, there are many situations where your application design or data schema require that you be able to randomly read or update a specific node. An obvious example is if your data is being stored in a large file where writing or reading every node would be impractical and inefficient. For those scenarios, there is the DOM. The .NET class library implements the DOM via the XmlDocument class that upcoming articles will cover.
About the Author
I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers.
Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.
Add www.codeguru.com to your favorites Add www.codeguru.com to your browser search box IE 7 | Firefox 2.0 | Firefox 1.5.xReceive news via our XML/RSS feed
RATE THIS ARTICLE:
Excellent Very Good Average Below Average Poor
(You must be signed in to rank an article. Not a member? Click here to register)
Latest Comments:
No Comments Posted.
Add a Comment:
Title:
Comment:
Pre-Formatted:
Check this if you want the text to display with the formatting as typed (good for source code)
(You must be signed in to comment on an article. Not a member? Click here to register)