You Are Here:

Community: Wiki

This page was last modified 10:44, 4 June 2009.

How to parse XML file using CParser class

From Forum Nokia Wiki

The following example shows how to parse XML file using Symbian OS C++ class, CParser. CParser is basically a SAX (Simple API for XML)-based XML parser.

It uses an active object to read the XML file chunk by chunk (see CXmlHandler::StartParsingWithAoL() method). On each chunk, it passes the buffer to the XML parser. When the XML parser finds an element, it calls the respective callback functions, for example CXmlHandler::OnStartElementL() or CXmlHandler::OnEndElementL().

To use CParser class, the XmlFramework.lib has to be included in the .mmp file. For more information about CParser, please visit some links at the end of this page.


Contents

XmlHandler.h

#ifndef __XMLHANDLER_H__
#define __XMLHANDLER_H__
 
// INCLUDE FILES
#include <e32base.h>
#include <f32file.h>  //Link against efsrv.lib 
#include <xml\contenthandler.h> // for MContentHandler
#include <xml\parser.h> // for CParser
 
// CLASS DECLARATION
 
using namespace Xml;
 
class CXmlHandler: public CActive, MContentHandler
    {
 
public: // Constructors and destructor
    
    static CXmlHandler* NewL();
    
    static CXmlHandler* NewLC();
    
    virtual ~CXmlHandler();
    
public: // Public methods
 
    void StartParsingWithAoL( const TDesC& aFileName );
    
private: // Constructors
 
    CXmlHandler();
    
    void ConstructL();
 
private: // from CActive
    
    void DoCancel();
    
    void RunL();
    
private: // from MContentHandler
 
    void OnStartDocumentL( const RDocumentParameters &aDocParam,
        TInt aErrorCode );
    
    void OnEndDocumentL( TInt aErrorCode );
    
    void OnStartElementL( const RTagInfo &aElement,
        const RAttributeArray &aAttributes, TInt aErrorCode );
        
    void OnEndElementL( const RTagInfo &aElement, TInt aErrorCode );
    
    void OnContentL( const TDesC8 &aBytes, TInt aErrorCode );
    
    void OnStartPrefixMappingL( const RString &aPrefix, const RString &aUri,
        TInt aErrorCode );
        
    void OnEndPrefixMappingL( const RString &aPrefix, TInt aErrorCode );
    
    void OnIgnorableWhiteSpaceL( const TDesC8 &aBytes, TInt aErrorCode );
    
    void OnSkippedEntityL( const RString &aName, TInt aErrorCode );
    
    void OnProcessingInstructionL( const TDesC8 &aTarget, const TDesC8 &aData,
        TInt aErrorCode);
        
    void OnError( TInt aErrorCode );
    
    TAny *GetExtendedInterface( const TInt32 aUid );
    
private: // Private data
 
    CParser*             iParser;
    HBufC8*              iBuffer;
    RFile                iFile;
 
    };
 
#endif /* __XMLHANDLER_H__ */


XmlHandler.cpp

// INCLUDE FILES
#include <coemain.h>
#include "XmlHandler.h"
 
// CONSTANTS
const TInt KFileBufferSize = 1024; // buffer size for file reading
_LIT8( KXmlMimeType, "text/xml" );
 
// METHODS DEFINITION
 
CXmlHandler* CXmlHandler::NewL()
    {
    CXmlHandler* self = CXmlHandler::NewLC();
    CleanupStack::Pop();
    return self;
    }
 
CXmlHandler* CXmlHandler::NewLC()
    {
    CXmlHandler* self = new ( ELeave ) CXmlHandler();
    CleanupStack::PushL( self );
    self->ConstructL();
    return self;
    }
 
CXmlHandler::~CXmlHandler()
    {
    Cancel();
    delete iParser;
    delete iBuffer;
    }
 
CXmlHandler::CXmlHandler()
    :CActive( EPriorityStandard )
    {
    CActiveScheduler::Add( this );
    }
 
void CXmlHandler::DoCancel()
    {
    iParser->ParseEndL();
    iFile.Close();
    delete iBuffer;
    iBuffer = 0;
    }
 
void CXmlHandler::RunL()
    {
    if ( KErrNone == iStatus.Int() )
        {
        // If the buffer length is zero, it means if we have reached
        // the end of the file.
        if ( iBuffer->Length() == 0)
            {
            iParser->ParseEndL();
            iFile.Close();
            delete iBuffer;
            iBuffer = 0;
            }
            
        // Otherwise, we continue reading the next chunk of the XML file.
        else
            {
            // Parse the next "part" of the XML document.
            iParser->ParseL( *iBuffer );
            
            // Read the next chunk of the file.
            TPtr8 bufferPtr( iBuffer->Des() );
            iFile.Read( bufferPtr, KFileBufferSize, iStatus );
            
            // Don't forget to call this... :)
            SetActive();
            }
        }
    else
        {
        // Do something if error happens.
        }
    }
 
void CXmlHandler::ConstructL()
    {
    iParser = CParser::NewL( KXmlMimeType, *this );
    }
 
void CXmlHandler::StartParsingWithAoL( const TDesC& aFileName )
    {
     // Remember to cancel any outstanding request first.
    if ( IsActive() )
        {
        Cancel();
        }
        
    User::LeaveIfError( iFile.Open( CCoeEnv::Static()->FsSession(), aFileName,
        EFileRead ) );
 
    // Create a buffer to store the file content.
    // Note that this method uses active object to read the file.
    // So we have to call SetActive() at the end. Then we call CParser::ParseL()
    // in RunL() method.
    delete iBuffer;
    iBuffer = 0;
    iBuffer = HBufC8::NewL( KFileBufferSize );
    TPtr8 bufferPtr( iBuffer->Des() );
    iFile.Read( bufferPtr, KFileBufferSize, iStatus );
    SetActive();
 
    // Tell the parser that we are about to parse a XML document.    
    iParser->ParseBeginL();
    }
 
void CXmlHandler::OnStartDocumentL( const RDocumentParameters& /*aDocParam*/,
        TInt aErrorCode )
    {
    if ( KErrNone == aErrorCode )
        {
        // Do something here when the parser at the start of the document.
        }
    else
        {
        // Do something if error happens.
        }
    }
 
void CXmlHandler::OnEndDocumentL( TInt aErrorCode )
    {
    if ( KErrNone == aErrorCode )
        {
        // Do something here when the parser reaches the end of the document.
        }
    }
 
void CXmlHandler::OnStartElementL( const RTagInfo& aElement,
        const RAttributeArray& /*aAttributes*/, TInt aErrorCode )
    {
    if ( KErrNone == aErrorCode )
        {
        // Found start of an element, for example: "<tag>"
        // The name of the element is stored in aElement.LocalName().DesC().
 
        // Do something with the start of an element.
        }
    else
        {
        // Do something if error happens.
        }
    }
        
void CXmlHandler::OnEndElementL( const RTagInfo &aElement, TInt aErrorCode )
    {
    if ( KErrNone == aErrorCode )
        {
        // Found the end of an element, for example: "</tag>"
        // The name of the element is stored in aElement.LocalName().DesC().
 
        // Do something with the end of an element.
        }
    else
        {
        // Do something if error happens.
        }
    }
    
void CXmlHandler::OnContentL( const TDesC8 &aBytes, TInt aErrorCode )
    {
    if ( KErrNone == aErrorCode )
        {
        // aBytes stored the value of the parsed contents.
        }
    else
        {
        // Display error messages here.
        }
    }
    
void CXmlHandler::OnStartPrefixMappingL( const RString& /*aPrefix*/,
        const RString& /*aUri*/, TInt aErrorCode )
    {
    }
        
void CXmlHandler::OnEndPrefixMappingL( const RString& /*aPrefix*/,
        TInt aErrorCode )
    {
    }
    
void CXmlHandler::OnIgnorableWhiteSpaceL( const TDesC8& /*aBytes*/,
        TInt aErrorCode )
    {
    }
    
void CXmlHandler::OnSkippedEntityL( const RString& /*aName*/,
        TInt aErrorCode )
    {
    }
 
void CXmlHandler::OnProcessingInstructionL( const TDesC8& /*aTarget*/,
        const TDesC8& /*aData*/, TInt aErrorCode )
    {
    }
 
void CXmlHandler::OnError( TInt aErrorCode )
    {
    // Do something if error happens.
    }
 
TAny* CXmlHandler::GetExtendedInterface( const TInt32 /*aUid*/ )
    {
    return 0;
    }

download example

See Also

Rate This

 
Bookmark this page: DeliciousDiggFacebookGoogleYahooStumbleUponRedditFurlTechnocratiMagnoliaTwitter  Share this page Share this page Print this Page Print this page Invite a friend Invite a friend
Email Newsletters Press Terms & Conditions Privacy Policy Sitemap Contact Us © 2009 Nokia 
RDF Facets: qdcZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qdcZidentifierQSxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2findeE78E2ephpE2fMMPE5ffileX qdcZpublisherQUxhttpE3aE2fE2fswE2enokiaE2ecomE2fidE2fc764fd1cE2d8b06E2d499aE2d9a6aE2d17c3903d5a65E2fforumE5fnokiaE5fcrawlerE5fagentX qdcZtitleQSxMMPE20fileE20E2dE20ForumE20NokiaE20WikiX qdcZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qdcZtypeQUqfnTypeZCommunityContentQ qdcZtypeQUqfnTypeZE52esourceQ qdcZtypeQUqfnTypeZWebpageQ qdcZtypeQUqfnTypeZWikiContentQ qdcZtypeQUqmarsZManagedE52esourceQ qdcZtypeQUqwebZInformationE52esourceQ qdcZtypeQUqwebZPageQ qdcZtypeQUqwebZE52esourceQ qdcZtypeQUqrdfsZE52esourceQ qrssZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qfnZdistributionQUxhttpE3aE2fE2fwikiE2eforumE2enokiaE2ecomE2fX qfnZtypeQUqfnTypeZCommunityContentQ qfnZtypeQUqfnTypeZE52esourceQ qfnZtypeQUqfnTypeZWebpageQ qfnZtypeQUqfnTypeZWikiContentQ qfnZupdatedQDx2008E2d10E2d02X qfnZuserE5ftagQSxfileX qfnZuserE5ftagQSxlibpathX qfnZuserE5ftagQSxmmpX qfnZuserE5ftagQSxresourceX qmarsZdescriptionQSxEa0E20WikiE20javaE20symbianE5fosE20s60E20maemoE20cE2bE2bE20WikiE20HomeE20WikiE20HelpE20OverviewE20GlossaryE20CreateE20PageE20ProposeE20anE20ArticleE20SpotlightE20TopicE20E2dE20WE52TE20WidgetsE20ProgrammingE20E4canguageE20E2dE20SymbianE20CE2bE2bE20E2dE20OpenE20CE2fCE2bE2bE20E2dE20JavaE20E2dE20FlashE20E4citeE20E2dE20PythonE20WebE20TechnologiesE20E2dE20WE52TE20WidgetsE20E2dE20WidSetsE20ToolsE20andE20SE44KE20CodeE20E45E78amplesE20KnowledgeE20BaseE20TechnologyE20AreasE20SoftwareE20PlatformsE20E44evelopmentE20ProcessE20E3fE3fWikiE20ChineseE20E3fE3fE3fWikiE20JapaneseE20PortugueseE2fBrazilianE20E52ussianE20WhatE20linksE20hereE20UploadE20fileE20SpecialE20pagesE20PrintableE20versionE44ownloadE20asE20PE44FE20GoE20ToE20E2eE2eE2eX qmarsZlanguageQUxhttpE3aE2fE2fswE2enokiaE2ecomE2flanguageE2d1E2fenX qrdfZtypeQUqfnZE45E78cludedFromGeneralE4cistingsQ qrdfZtypeQUqfnTypeZCommunityContentQ qrdfZtypeQUqfnTypeZE52esourceQ qrdfZtypeQUqfnTypeZWebpageQ qrdfZtypeQUqfnTypeZWikiContentQ qrdfZtypeQUqmarsZManagedE52esourceQ qrdfZtypeQUqwebZInformationE52esourceQ qrdfZtypeQUqwebZPageQ qrdfZtypeQUqwebZE52esourceQ qrdfZtypeQUqrdfsZE52esourceQ