CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> Visual C++ / C++ >> C++ >> Managed C++ >> Processes & Threads


Build a Maintenance Application with the XmlTextWriter/XmlTextReader Classes
Rating:

Tom Archer - MSFT (view profile)
May 27, 2005

Go to page: Prev  1  2  

  1. 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 needed—such as when writing nested elements or elements with attributes—the 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 new
      if (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")
    }
  2. 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":

    void CVideoInfoDlg::OnBnClickedOpen()
    {
    #pragma push_macro("new")
    #undef new
      CFileDialog dlg(TRUE);
      dlg.m_pOFN->lpstrInitialDir = m_strWorkingDir;
      dlg.m_pOFN->lpstrTitle = _T("Open a VideoInfo XML File");
      dlg.m_pOFN->lpstrFilter = _T("XML Files (*.xml)\0*.xml\0");
    
      if (IDOK == dlg.DoModal())
      {
        m_lbxActors.ResetContent();
    
        XmlTextReader* xmlreader;
        try
        {
          xmlreader  = new XmlTextReader(dlg.GetPathName());
    
          while (xmlreader->Read())
          {
            if (XmlNodeType::Element == xmlreader->NodeType)
            {
              CString name = (CString)xmlreader->Name;
    
              if (0 == name.CompareNoCase(_T("VideoInfo")))
                m_strFormat = (CString)xmlreader->
                              GetAttribute(S"Format");
    
              else if (0 == name.CompareNoCase(_T("Title")))
                m_strTitle = (CString)xmlreader->ReadString();
    
              else if (0 == name.CompareNoCase(_T("Director")))
                m_strDirector = (CString)xmlreader->ReadString();
    
              else if (0 == name.CompareNoCase(_T("Actor")))
                m_lbxActors.AddString((CString)xmlreader->
                ReadString());
    
              else if (0 == name.CompareNoCase(_T("Studio")))
                m_strStudio = (CString)xmlreader->ReadString();
    
              else if (0 == name.CompareNoCase(_T("ReleaseYear")))
                m_iReleaseYear = Convert::ToInt32(xmlreader->
                                 ReadString());
    
              else if (0 == name.CompareNoCase(_T("Runtime")))
                m_iRuntime = Convert::ToInt32(xmlreader->
                             ReadString());
            }
          }
          UpdateData(FALSE);
        }
        catch(Exception* e)
        {
          MessageBox::Show(e->Message);
        }
        __finally
        {
          xmlreader->Close();
        }
      }
    #pragma pop_macro("new")
    }
  3. 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.

Go to page: Prev  1  2  

Downloads

  • VideoInfo.zip - Download source code - 47 Kb

    Tools:
    Add www.codeguru.com to your favorites
    Add www.codeguru.com to your browser search box
    IE 7 | Firefox 2.0 | Firefox 1.5.x
    Receive 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)


    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    IBM Whitepaper: Innovative Collaboration to Advance Your Business
    Internet.com eBook: Real Life Rails
    Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
    Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
    Internet.com eBook: The Pros and Cons of Outsourcing
    Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
    Internet.com eBook: Best Practices for Developing a Web Site
    IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
    Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
    Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
    IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
    Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
    Go Parallel Article: Getting Started with TBB on Windows
    HP eBook: Storage Networking , Part 1
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
    HP Video: Is Your Data Center Ready for a Real World Disaster?
    Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
    HP On Demand Webcast: Virtualization in Action
    Go Parallel Video: Performance and Threading Tools for Game Developers
    Rackspace Hosting Center: Customer Videos
    Intel vPro Developer Virtual Bootcamp
    HP Disaster-Proof Solutions eSeminar
    HP On Demand Webcast: Discover the Benefits of Virtualization
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Microsoft Download: Silverlight 2 Software Development Kit Beta 2
    30-Day Trial: SPAMfighter Exchange Module
    Red Gate Download: SQL Toolbelt
    Iron Speed Designer Application Generator
    Microsoft Download: Silverlight 2 Beta 2 Runtime
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
    Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
    Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES