CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

follow us on Twitter

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
















Home >> Visual C++ / C++ >> Graphics & Multimedia >> Multimedia >> Video


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)